Compare commits
40 Commits
theme
...
33285ad590
| Author | SHA1 | Date | |
|---|---|---|---|
| 33285ad590 | |||
| 138c98ccec | |||
| f3fc8dfe18 | |||
| c79b0aedf6 | |||
| 2c27dbc6e4 | |||
| 3c8fc1802d | |||
| a20e5a772e | |||
| 31bf6b9f41 | |||
| 7c79bc7cc0 | |||
| 7c4c9563fe | |||
| e79d5ae63e | |||
| 3cc687aff5 | |||
| 163bb9dfa0 | |||
| aff03d9c5c | |||
| bfa13302e1 | |||
| 5d79abe318 | |||
| f811ee2e8c | |||
| 557bc15972 | |||
| 215af86e55 | |||
| 3436df38e5 | |||
| 81f1a96df1 | |||
| f38e8f798b | |||
| 27a975138a | |||
| eedc15bc13 | |||
| 01ef4e9260 | |||
| b59b6eb017 | |||
| f41d1ef384 | |||
| 4b8b31abe7 | |||
| 01d3c5cec2 | |||
| 866a8d3083 | |||
| 045f9522c4 | |||
| bc4af45c01 | |||
| cc7c1d36af | |||
| 33a6710909 | |||
| 8dbac9379f | |||
| d22b8adada | |||
| fb0afbcb3c | |||
| dd438e6586 | |||
| f4351613a3 | |||
| e7a10f5478 |
+8
-3
@@ -38,6 +38,8 @@ const pub = a => a ? { email: a.email, sponsorRef: a.sponsorRef || '', code: a.c
|
|||||||
avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null,
|
avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null,
|
||||||
profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js)
|
profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js)
|
||||||
chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0,
|
chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0,
|
||||||
|
firstSeen: a.firstSeen || 0, // 2026-11-05: earliest known signed-in visit (backfilled from lastSeen on the next visit); the Founder badge reads it
|
||||||
|
founder: a.founder || 0, // 2026-11-05: Founder badge granted (ms of the launch moment it was granted for); cosmetic only (launchweek.js)
|
||||||
theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (cr-shell.js)
|
theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (cr-shell.js)
|
||||||
address: a.address || null, created: a.created } : null;
|
address: a.address || null, created: a.created } : null;
|
||||||
const USER_RE = /^[a-zA-Z0-9_]{3,20}$/;
|
const USER_RE = /^[a-zA-Z0-9_]{3,20}$/;
|
||||||
@@ -129,7 +131,8 @@ const J = {
|
|||||||
this.save();
|
this.save();
|
||||||
return { ok: true, account: pub(acct) };
|
return { ok: true, account: pub(acct) };
|
||||||
},
|
},
|
||||||
async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { a.lastSeen = Date.now(); this.save(); } },
|
async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { const now = Date.now(); if (!a.firstSeen) a.firstSeen = a.lastSeen || now; a.lastSeen = now; this.save(); } }, // firstSeen keeps the earliest signed-in visit we know of
|
||||||
|
async setFounder(e, ts) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; if (a.founder) return { ok: true, already: true }; a.founder = Number(ts) || Date.now(); this.save(); return { ok: true }; },
|
||||||
async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; },
|
async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; },
|
||||||
async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; },
|
async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; },
|
||||||
async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; },
|
async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; },
|
||||||
@@ -235,7 +238,7 @@ const rowPub = r => r ? pub({ email: r.email, sponsorRef: r.sponsor_ref, code: r
|
|||||||
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null,
|
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null,
|
||||||
lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null,
|
lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null,
|
||||||
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, profileQuarantined: !!r.profile_quarantined,
|
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, profileQuarantined: !!r.profile_quarantined,
|
||||||
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null,
|
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null, firstSeen: Number(r.first_seen || 0), founder: Number(r.founder || 0),
|
||||||
address: r.address, created: Number(r.created) }) : null;
|
address: r.address, created: Number(r.created) }) : null;
|
||||||
const D = {
|
const D = {
|
||||||
async signup(e, password, ref) {
|
async signup(e, password, ref) {
|
||||||
@@ -296,7 +299,8 @@ const D = {
|
|||||||
if (quarantined !== undefined) await db.q('UPDATE accounts SET profile_quarantined=? WHERE email=?', [quarantined ? 1 : 0, e]);
|
if (quarantined !== undefined) await db.q('UPDATE accounts SET profile_quarantined=? WHERE email=?', [quarantined ? 1 : 0, e]);
|
||||||
return { ok: true, account: await this.byEmail(e) };
|
return { ok: true, account: await this.byEmail(e) };
|
||||||
},
|
},
|
||||||
async touchSeen(e) { await db.q('UPDATE accounts SET last_seen=? WHERE email=?', [Date.now(), e]); },
|
async touchSeen(e) { const now = Date.now(); await db.q('UPDATE accounts SET first_seen=COALESCE(first_seen, last_seen, ?), last_seen=? WHERE email=?', [now, now, e]); }, // SET runs left to right: first_seen takes the OLD last_seen
|
||||||
|
async setFounder(e, ts) { const r = await db.q('UPDATE accounts SET founder=? WHERE email=? AND (founder IS NULL OR founder=0)', [Number(ts) || Date.now(), e]); return { ok: true, already: !(r && r.affectedRows) }; },
|
||||||
async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; },
|
async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; },
|
||||||
async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; },
|
async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; },
|
||||||
async getMutes(e) {
|
async getMutes(e) {
|
||||||
@@ -497,6 +501,7 @@ module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, by
|
|||||||
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
||||||
setProfile: (e, a, bio, socials, quarantined) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined).then(tap(String(e || '').toLowerCase())),
|
setProfile: (e, a, bio, socials, quarantined) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined).then(tap(String(e || '').toLowerCase())),
|
||||||
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
|
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
|
||||||
|
setFounder: (e, ts) => impl().setFounder(String(e || '').toLowerCase(), ts), // cosmetic Founder flag (launchweek.js); no onChange tap
|
||||||
setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no onChange tap, InstantAdPay does not mirror it
|
setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no onChange tap, InstantAdPay does not mirror it
|
||||||
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null).then(tap(String(e || '').toLowerCase())),
|
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null).then(tap(String(e || '').toLowerCase())),
|
||||||
positionByAddress: a => impl().positionByAddress(normAddr(a)),
|
positionByAddress: a => impl().positionByAddress(normAddr(a)),
|
||||||
|
|||||||
+17
-4
@@ -199,8 +199,9 @@ function pub(s, extra) {
|
|||||||
}
|
}
|
||||||
async function list(owner) { return mine(owner).map(s => pub(s)); }
|
async function list(owner) { return mine(owner).map(s => pub(s)); }
|
||||||
async function create(owner, body) {
|
async function create(owner, body) {
|
||||||
|
// the owner (ADMIN_EMAIL) has no Banner Spin count cap (Marty 2026-11-09, same as the upload exemption); members keep their tier's count
|
||||||
const t = await tierFor(owner); if (!t.ok) return { error: t.reason, tier: t };
|
const t = await tierFor(owner); if (!t.ok) return { error: t.reason, tier: t };
|
||||||
if (mine(owner).length >= t.spins) return { error: 'Your ' + t.label + ' tier holds ' + t.spins + ' Banner Spins.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.spins + '.' : ''), tier: t };
|
if (!(ADMIN && norm(owner) === ADMIN) && mine(owner).length >= t.spins) return { error: 'Your ' + t.label + ' tier holds ' + t.spins + ' Banner Spins.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.spins + '.' : ''), tier: t };
|
||||||
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the Banner Spin a name.' };
|
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the Banner Spin a name.' };
|
||||||
const size = String(body.size || ''); if (!SIZES[size]) return { error: 'Pick one of the sizes: ' + Object.keys(SIZES).join(', ') + '.' };
|
const size = String(body.size || ''); if (!SIZES[size]) return { error: 'Pick one of the sizes: ' + Object.keys(SIZES).join(', ') + '.' };
|
||||||
const s = { id: J.db.spins.reduce((m, x) => Math.max(m, x.id), 0) + 1, owner: norm(owner), name, code: newCode(), size, mode: body.mode === 'visitor' ? 'visitor' : 'weight', fallback: httpsUrl(body.fallback) || '', fallbackImage: '', banners: [], nextBanner: 1, paused: false, created: Date.now() };
|
const s = { id: J.db.spins.reduce((m, x) => Math.max(m, x.id), 0) + 1, owner: norm(owner), name, code: newCode(), size, mode: body.mode === 'visitor' ? 'visitor' : 'weight', fallback: httpsUrl(body.fallback) || '', fallbackImage: '', banners: [], nextBanner: 1, paused: false, created: Date.now() };
|
||||||
@@ -331,7 +332,7 @@ async function click(code, req, reqHost) {
|
|||||||
url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
|
url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
|
||||||
try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {}
|
try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {}
|
||||||
// straight to a page: the click id rides along for the landing tag (a spin-link target adds its own on the /r/ hop)
|
// straight to a page: the click id rides along for the landing tag (a spin-link target adds its own on the /r/ hop)
|
||||||
if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner)) url = WITH_CLICK_ID(url, id); } catch (e) {} } }
|
if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner, url)) url = WITH_CLICK_ID(url, id); } catch (e) {} } }
|
||||||
}
|
}
|
||||||
return { url, lsid: id, banner: b, matched: m, owner: s.owner };
|
return { url, lsid: id, banner: b, matched: m, owner: s.owner };
|
||||||
}
|
}
|
||||||
@@ -348,10 +349,13 @@ function clickById(id) {
|
|||||||
async function convert(lsid, ev, facts) {
|
async function convert(lsid, ev, facts) {
|
||||||
const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null;
|
const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null;
|
||||||
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
|
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
|
||||||
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined, key: facts && facts.key ? String(facts.key) : undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||||
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
|
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a member's Banner Spin conversions as rows (netconv.unified); rows with a key are the ledger's and are skipped there
|
||||||
|
function convRows(owner, since) { const ids = new Set(J.db.spins.filter(x => x.owner === String(owner || '').trim().toLowerCase()).map(x => x.id)); return J.db.conv.filter(c => ids.has(c.s) && c.ts >= since); }
|
||||||
|
|
||||||
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
|
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
|
||||||
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
|
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
|
||||||
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
|
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
|
||||||
@@ -454,6 +458,15 @@ function settings() { return { off: !!J.db.settings.off, grants: J.db.grants };
|
|||||||
// image files Banner Spins use, for the admin upload list (file name -> owner + where)
|
// image files Banner Spins use, for the admin upload list (file name -> owner + where)
|
||||||
function imageRefs() { const out = {}; for (const s of J.db.spins) for (const im of s.banners.map(b => b.image).concat(s.fallbackImage || [])) { const m = LOCAL_IMG.exec(im || ''); if (m) out[m[1]] = { email: s.owner, where: 'Banner Spin ' + s.code }; } for (const [n, r] of Object.entries(J.db.images)) if (!out[n]) out[n] = { email: r.owner, where: '' }; return out; }
|
function imageRefs() { const out = {}; for (const s of J.db.spins) for (const im of s.banners.map(b => b.image).concat(s.fallbackImage || [])) { const m = LOCAL_IMG.exec(im || ''); if (m) out[m[1]] = { email: s.owner, where: 'Banner Spin ' + s.code }; } for (const [n, r] of Object.entries(J.db.images)) if (!out[n]) out[n] = { email: r.owner, where: '' }; return out; }
|
||||||
function totals() { return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), clicks: J.db.clicks.length }; }
|
function totals() { return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), clicks: J.db.clicks.length }; }
|
||||||
|
// site-wide figures for the daily snapshot: impressions counted today (Central day, merged counts + pending deltas),
|
||||||
|
// clicks and new Banner Spins inside the `since` window
|
||||||
|
function window24(since) {
|
||||||
|
const day = ctDay(); let imps = 0;
|
||||||
|
const add = store => { try { for (const sid of Object.keys((store && store.d) || {})) { const r = (store.d[sid] || {})[day]; if (r && r.b) for (const k of Object.keys(r.b)) imps += Number(r.b[k]) || 0; } } catch (e) {} };
|
||||||
|
add(C.db); add(PENDING);
|
||||||
|
const clicks = J.db.clicks.filter(c => c.ts >= since && !c.bot);
|
||||||
|
return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), created: J.db.spins.filter(s => (s.created || 0) >= since).length, impsToday: imps, clicks: clicks.length };
|
||||||
|
}
|
||||||
|
|
||||||
// a transparent PNG at the exact banner size, for the blank image (admin off, nothing to show); cached per size
|
// a transparent PNG at the exact banner size, for the blank image (admin off, nothing to show); cached per size
|
||||||
const BLANK = new Map();
|
const BLANK = new Map();
|
||||||
@@ -480,4 +493,4 @@ const rawSpins = () => J.db.spins;
|
|||||||
const save = () => J.save();
|
const save = () => J.save();
|
||||||
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
|
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
|
||||||
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
|
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
|
||||||
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
|
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, window24, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
|
||||||
|
|||||||
@@ -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=20261101t"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
return '</div><script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
}
|
}
|
||||||
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="LinkSpin"><div><b>' + AUTHOR + '</b><span>Founder of LinkSpin 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="LinkSpin"><div><b>' + AUTHOR + '</b><span>Founder of LinkSpin 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>';
|
||||||
|
|||||||
+48
-18
File diff suppressed because one or more lines are too long
@@ -242,7 +242,7 @@ async function nudgeTick() {
|
|||||||
// weekly member email (Marty, 2026-09-14, modelled on the mailer.gold weekly): credits sitting unspent,
|
// weekly member email (Marty, 2026-09-14, modelled on the mailer.gold weekly): credits sitting unspent,
|
||||||
// the streak, the contest standings with the member's own rank, the tank, and the line for sponsors
|
// the streak, the contest standings with the member's own rank, the tank, and the line for sponsors
|
||||||
let lbWeek = null; try { lbWeek = X.lb ? await X.lb().view('week') : null; } catch (e) {}
|
let lbWeek = null; try { lbWeek = X.lb ? await X.lb().view('week') : null; } catch (e) {}
|
||||||
let tankN = 0; try { tankN = X.tank ? (await X.tank.waiting()).length : 0; } catch (e) {}
|
let tankN = 0; try { tankN = X.tank ? (await X.tank.adoptable()).length : 0; } catch (e) {}
|
||||||
for (const acct of all) {
|
for (const acct of all) {
|
||||||
if (!acct.email || !acct.lastSeen) continue; // weekly mail only to people who have actually signed in here
|
if (!acct.email || !acct.lastSeen) continue; // weekly mail only to people who have actually signed in here
|
||||||
const lastD = await impl().lastDigest(acct.email);
|
const lastD = await impl().lastDigest(acct.email);
|
||||||
|
|||||||
+11
-1
@@ -270,6 +270,16 @@ async function report(owner, days, opts) {
|
|||||||
return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })),
|
return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })),
|
||||||
byGoal: out, methods, total: conv.length, selfTests };
|
byGoal: out, methods, total: conv.length, selfTests };
|
||||||
}
|
}
|
||||||
|
// goal conversions as rows, own-click tests left out. goalRows() = every row that came through a spin link, in the rotator's own
|
||||||
|
// shape, so per-link counts include goals (2026-11-07); memoized on the length of the log, the pixel only ever appends to it.
|
||||||
|
let GR = { n: -1, rows: [] };
|
||||||
|
function goalRows() { const c = load().conv; if (GR.n !== c.length) GR = { n: c.length, rows: c.filter(x => x.rot && !x.self).map(x => ({ r: x.rot, lsid: x.click, ev: 'goal: ' + x.goal, ts: x.ts, value: x.value || 0, sr: x.sr })) }; return GR.rows; }
|
||||||
|
function goalRowsOf(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self); }
|
||||||
|
// the click-side test of "is this the owner's own": the click was theirs, or the converting browser is one they sign in from
|
||||||
|
function selfFor(L, owner, sk) {
|
||||||
|
const st = load(), ad = L.ad, o = norm(owner);
|
||||||
|
return !!(st.selfIds[L.id] || st.selfIds[L.root] || (ad && ad.owner === o && (ad.self || (ad.sk && isOwnerSk(o, ad.sk)))) || (sk && isOwnerSk(o, sk)));
|
||||||
|
}
|
||||||
// InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner
|
// InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner
|
||||||
// goal conversions (not the owner's own tests) since a moment, for the Engine Room's goals dial (2026-10-24)
|
// goal conversions (not the owner's own tests) since a moment, for the Engine Room's goals dial (2026-10-24)
|
||||||
function countSince(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self).length; }
|
function countSince(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self).length; }
|
||||||
@@ -305,4 +315,4 @@ function withClickId(target, id) {
|
|||||||
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
||||||
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
||||||
}
|
}
|
||||||
module.exports = { noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };
|
module.exports = { goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };
|
||||||
|
|||||||
@@ -253,6 +253,8 @@ async function bootstrap() {
|
|||||||
// per-account chat settings: availability toggle (default on) + muted-member list (JSON emails)
|
// per-account chat settings: availability toggle (default on) + muted-member list (JSON emails)
|
||||||
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_available TINYINT NOT NULL DEFAULT 1');
|
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_available TINYINT NOT NULL DEFAULT 1');
|
||||||
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_mutes VARCHAR(4000) NULL');
|
await alterSafe('ALTER TABLE accounts ADD COLUMN chat_mutes VARCHAR(4000) NULL');
|
||||||
|
await alterSafe('ALTER TABLE accounts ADD COLUMN first_seen BIGINT NULL'); // earliest signed-in visit (Founder badge, 2026-11-05)
|
||||||
|
await alterSafe('ALTER TABLE accounts ADD COLUMN founder BIGINT NULL'); // Founder badge granted at (ms)
|
||||||
await q(`CREATE TABLE IF NOT EXISTS video_seen (
|
await q(`CREATE TABLE IF NOT EXISTS video_seen (
|
||||||
email VARCHAR(190) NOT NULL,
|
email VARCHAR(190) NOT NULL,
|
||||||
campaign_id INT NOT NULL,
|
campaign_id INT NOT NULL,
|
||||||
|
|||||||
@@ -108,10 +108,12 @@ function apply(r, d, c) {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
const toldToday = new Set();
|
||||||
async function tell(r, d, change) {
|
async function tell(r, d, change) {
|
||||||
if (!notify || !change || change.kind !== 'paused' || /^demo:/.test(r.owner)) return;
|
if (!notify || !change || change.kind !== 'paused' || /^demo:/.test(r.owner)) return;
|
||||||
|
const tk = r.id + ':' + ctDay(Date.now()); if (toldToday.has(tk)) return; toldToday.add(tk); if (toldToday.size > 5000) toldToday.clear(); // at most one pause email per link per day (2026-11-11: imported links carry hundreds of pages)
|
||||||
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
const html = '<p>LinkSpin paused one destination in your link <b>' + esc(r.name) + '</b> (/r/' + esc(r.code) + ') because it failed three checks in a row.</p>'
|
const html = '<p>LinkSpin paused one destination in your link <b>' + esc(r.name) + '</b> (/r/' + esc(r.code) + ') because it failed three checks in a row. (You get at most one of these emails per link per day; the link\'s Destinations tab shows every paused page.)</p>'
|
||||||
+ '<p><span style="font-family:monospace">' + esc(d.url) + '</span><br>' + esc(d.health.note || d.health.state) + '</p>'
|
+ '<p><span style="font-family:monospace">' + esc(d.url) + '</span><br>' + esc(d.health.note || d.health.state) + '</p>'
|
||||||
+ '<p>Visitors keep flowing to your other destinations' + (r.fallback ? ' and the fallback' : '') + '. If the page comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the address or resume it yourself under Links.</p>';
|
+ '<p>Visitors keep flowing to your other destinations' + (r.fallback ? ' and the fallback' : '') + '. If the page comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the address or resume it yourself under Links.</p>';
|
||||||
try { await notify(r.owner, 'A destination in ' + r.name + ' was paused', html); } catch (e) {}
|
try { await notify(r.owner, 'A destination in ' + r.name + ' was paused', html); } catch (e) {}
|
||||||
@@ -241,6 +243,7 @@ async function checkRotation(owner, id) {
|
|||||||
lastManual.set(r.id, Date.now());
|
lastManual.set(r.id, Date.now());
|
||||||
const jobs = r.destinations.map(d => async () => { const c = await check(d.url); const ch = apply(r, d, c); if (ch) await tell(r, d, ch); });
|
const jobs = r.destinations.map(d => async () => { const c = await check(d.url); const ch = apply(r, d, c); if (ch) await tell(r, d, ch); });
|
||||||
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; });
|
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; });
|
||||||
|
if (jobs.length > 50) { runAll(jobs).then(() => rotator.save()).catch(() => {}); return { ok: true, background: true, rotation: rotator.pub(r) }; } // a big link would outlive the request
|
||||||
await runAll(jobs); rotator.save();
|
await runAll(jobs); rotator.save();
|
||||||
return { ok: true, rotation: rotator.pub(r) };
|
return { ok: true, rotation: rotator.pub(r) };
|
||||||
}
|
}
|
||||||
|
|||||||
+193
@@ -0,0 +1,193 @@
|
|||||||
|
// Network hub link (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity; the contract
|
||||||
|
// sponsor is the truth; with no binding, the earliest join wins). Two directions, both OFF unless HUB_ENABLED=1:
|
||||||
|
// IN POST /api/hub/events body {events:[{seq, at, type, personId, data}]}, headers X-Hub-Ts (ms) + X-Hub-Sig = hex
|
||||||
|
// HMAC-SHA256(ts + "\n" + rawBody) with HUB_SECRET (network-hub lib/signing.js). Older than 5 minutes = refused. The hub
|
||||||
|
// only moves its cursor on a 2xx, so events can arrive twice: each seq is applied once (DATA_DIR/hubsync.json lastSeq).
|
||||||
|
// member.joined from another door: /v1/resolve {id} for the person, then the SAME waiting (shell) account the InstantAdPay
|
||||||
|
// registry sync makes (/api/partner/registry in server.js): accounts.ensure(email, '', 'carried', 'network'), then only
|
||||||
|
// EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed
|
||||||
|
// first (up to 25 levels up) so the line exists. A sponsor already set here is never moved: a disagreement is logged.
|
||||||
|
// wallet.connected: fills an empty wallet here, same as the registry sync. Every other event is acknowledged and ignored.
|
||||||
|
// OUT accounts.onChange -> touch(email): a persisted outbox (DATA_DIR/hubsync.json) reports LinkSpin's own joins
|
||||||
|
// (/v1/join, sponsor named by email) and wallet links (/v1/wallet). Never blocks sign-up; failures retry with backoff.
|
||||||
|
// The InstantAdPay<->LinkSpin sync (iapsync.js, /api/partner/registry) is not touched by any of this.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
let R = null, state = null, timer = null, flushing = false, inbound = Promise.resolve();
|
||||||
|
const ENABLED = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_ENABLED || '').trim());
|
||||||
|
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const SITE = () => String(process.env.HUB_SITE || 'linkspin').trim().toLowerCase();
|
||||||
|
const on = () => ENABLED() && SECRET().length >= 32 && /^https?:\/\//.test(URL_());
|
||||||
|
const WINDOW_MS = 5 * 60 * 1000;
|
||||||
|
const MAX_UP = 25; // how far up a sponsor line is placed for one event (bad data must not hang a request)
|
||||||
|
const FILE = () => path.join(R.dataDir, 'hubsync.json');
|
||||||
|
const norm = v => String(v || '').trim().toLowerCase();
|
||||||
|
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); // logs and the admin view never show a full address
|
||||||
|
function load() {
|
||||||
|
if (state) return state;
|
||||||
|
try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = null; }
|
||||||
|
if (!state || typeof state !== 'object') state = {};
|
||||||
|
state.lastSeq = Number(state.lastSeq) || 0; state.outbox = state.outbox || {}; state.sent = state.sent || {};
|
||||||
|
state.disagree = state.disagree || {}; state.stats = state.stats || { events: 0, shells: 0, filled: 0, joins: 0, wallets: 0, dropped: 0, errors: 0 };
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
||||||
|
function init(deps) { R = deps; state = null; load(); } // { dataDir, accounts, registry, carry, follow (sponsorfollow store) }
|
||||||
|
|
||||||
|
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
||||||
|
async function call(route, body) {
|
||||||
|
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||||
|
let r;
|
||||||
|
try { r = await fetch(URL_() + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(15000) }); }
|
||||||
|
catch (e) { throw new Error('hub ' + route + ' unreachable'); }
|
||||||
|
let out = null; try { out = await r.json(); } catch (e) {}
|
||||||
|
if (r.status >= 500 || r.status === 401) throw new Error('hub ' + route + ' ' + r.status); // down, redeploying (503) or misconfigured: try again later
|
||||||
|
return { status: r.status, body: out || {} };
|
||||||
|
}
|
||||||
|
async function resolveId(id) {
|
||||||
|
if (!id) return null;
|
||||||
|
const r = await call('/v1/resolve', { id });
|
||||||
|
return r.status === 200 && r.body.person ? r.body.person : null;
|
||||||
|
}
|
||||||
|
const refEmail = async ref => { if (!ref) return null; const a = (await R.accounts.byUsername(ref)) || (await R.accounts.byCode(ref)); return a ? norm(a.email) : null; };
|
||||||
|
function noteDisagree(e, hubSponsor, here, how) {
|
||||||
|
load().disagree[e] = { at: Date.now(), hub: hubSponsor || null, here: here || null, how }; save();
|
||||||
|
console.log('hubsync sponsor differs', how, mask(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- inbound -------------------------------------------------------------------------------------------------------------
|
||||||
|
// a hub person gets a LinkSpin account the way an InstantAdPay person does: a waiting shell, empty fields filled, nothing moved
|
||||||
|
async function place(p, depth, seen) {
|
||||||
|
const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e);
|
||||||
|
let sp = p.sponsor && p.sponsor.email ? await R.accounts.byEmail(p.sponsor.email) : null;
|
||||||
|
if (!sp && p.sponsor && p.sponsor.id && depth < MAX_UP) { // the sponsor is new here too: their line first
|
||||||
|
const up = await resolveId(p.sponsor.id);
|
||||||
|
if (up && up.email) { await place(up, depth + 1, seen); sp = await R.accounts.byEmail(up.email); }
|
||||||
|
}
|
||||||
|
R.carry.hold([e]);
|
||||||
|
try {
|
||||||
|
if (!(await R.registry.get(e))) { // a new row only: the registry is what InstantAdPay told us, iapsync's loop guard reads it
|
||||||
|
try { await R.registry.upsert({ email: e, username: p.username || null, wallet: p.wallet || null, sponsorEmail: sp ? sp.email : null, joinedAt: p.firstDoor && p.firstDoor.at, firstProperty: (p.firstDoor && p.firstDoor.site) || 'network' }); } catch (err) {}
|
||||||
|
}
|
||||||
|
let a = await R.accounts.byEmail(e);
|
||||||
|
if (!a) { const x = await R.accounts.ensure(e, '', 'carried', 'network'); if (x.created) load().stats.shells++; a = await R.accounts.byEmail(e); }
|
||||||
|
if (!a) return null;
|
||||||
|
if (p.username && !a.username) { try { const r = await R.accounts.setUsername(e, p.username); if (r && !r.error) load().stats.filled++; } catch (err) {} }
|
||||||
|
if (sp && norm(sp.email) !== e) {
|
||||||
|
if (!a.sponsorRef) {
|
||||||
|
const pv = R.follow && R.follow.get(e); // emptied on purpose here (released / rescued): an ordinary fill does not refill it
|
||||||
|
const deliberate = pv && pv.by && ['adopt', 'rescue', 'release', 'expiry', 'admin'].includes(pv.by) && !pv.sponsorEmail;
|
||||||
|
if (!deliberate && (sp.username || sp.code)) { try { await R.accounts.setSponsorRef(e, sp.username || sp.code); load().stats.filled++; } catch (err) {} }
|
||||||
|
} else {
|
||||||
|
const here = await refEmail(a.sponsorRef);
|
||||||
|
if (here !== norm(sp.email)) noteDisagree(e, sp.email, here, 'inbound'); // LinkSpin's line stands; TODO(Marty): who settles these
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p.wallet && !a.address) { try { const r = await R.accounts.linkWallet(e, p.wallet); if (r && !r.error) load().stats.filled++; } catch (err) {} }
|
||||||
|
return a;
|
||||||
|
} finally { R.carry.unhold([e]); }
|
||||||
|
}
|
||||||
|
async function apply(ev) {
|
||||||
|
const type = String(ev.type || '');
|
||||||
|
if (type === 'member.joined') {
|
||||||
|
if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back
|
||||||
|
const p = await resolveId(ev.personId);
|
||||||
|
if (p && p.email) await place(p, 0, new Set());
|
||||||
|
} else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync
|
||||||
|
const p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return;
|
||||||
|
const a = await R.accounts.byEmail(p.email);
|
||||||
|
if (a && !a.address) { R.carry.hold([a.email]); try { await R.accounts.linkWallet(a.email, p.wallet); } finally { R.carry.unhold([a.email]); } }
|
||||||
|
}
|
||||||
|
// TODO(hub): sponsor.changed needs the sponsorfollow.js decision (chain binding, window, provenance); until it is wired, ignored.
|
||||||
|
// TODO(hub): member.blocked / unblocked, entitlement.changed, wallet.changed and the wallet-change events: ignored for now.
|
||||||
|
}
|
||||||
|
function verify(headers, raw) {
|
||||||
|
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
||||||
|
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > WINDOW_MS) return false;
|
||||||
|
const want = sign(ts, raw);
|
||||||
|
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||||
|
}
|
||||||
|
// -> {status, body}. One batch at a time, in seq order; a seq already applied is skipped. A hub that cannot be reached
|
||||||
|
// answers 503 so the hub sends the batch again; a bad event is counted and passed (it must not stop every later one).
|
||||||
|
function receive(headers, raw) {
|
||||||
|
const run = inbound.then(async () => {
|
||||||
|
if (!on()) return { status: 404, body: { error: 'not_found' } };
|
||||||
|
if (!verify(headers, raw)) return { status: 401, body: { error: 'unauthorized' } };
|
||||||
|
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return { status: 400, body: { error: 'bad_json' } }; }
|
||||||
|
const st = load(); const events = (Array.isArray(b.events) ? b.events : []).slice().sort((x, y) => Number(x.seq) - Number(y.seq));
|
||||||
|
let applied = 0, skipped = 0;
|
||||||
|
for (const ev of events) {
|
||||||
|
const seq = Number(ev && ev.seq) || 0;
|
||||||
|
if (!seq || seq <= st.lastSeq) { skipped++; continue; }
|
||||||
|
try { await apply(ev); applied++; st.stats.events++; }
|
||||||
|
catch (e) {
|
||||||
|
if (/^hub /.test(e.message)) { save(); return { status: 503, body: { error: 'retry', seq } }; }
|
||||||
|
st.stats.errors++; st.lastError = { at: Date.now(), seq, error: String(e.message).slice(0, 160) }; console.error('hubsync event', seq, e.message);
|
||||||
|
}
|
||||||
|
st.lastSeq = seq; save();
|
||||||
|
}
|
||||||
|
return { status: 200, body: { ok: true, applied, skipped, lastSeq: st.lastSeq } };
|
||||||
|
});
|
||||||
|
inbound = run.catch(() => {});
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- outbound ------------------------------------------------------------------------------------------------------------
|
||||||
|
function touch(email) {
|
||||||
|
if (!on() || !email) return;
|
||||||
|
const e = norm(email); const st = load();
|
||||||
|
if (!st.outbox[e]) { st.outbox[e] = { at: Date.now(), tries: 0, next: 0 }; save(); }
|
||||||
|
if (!timer) timer = setTimeout(() => { timer = null; flush().catch(err => console.error('hubsync flush', err.message)); }, 3000);
|
||||||
|
}
|
||||||
|
async function report(e) {
|
||||||
|
const a = await R.accounts.byEmail(e); if (!a) return;
|
||||||
|
const st = load(); const s = st.sent[e] || {};
|
||||||
|
if (a.joinedVia !== 'carried') { // a waiting copy of someone from another door: that door reports them
|
||||||
|
const sp = a.sponsorRef ? await R.accounts.sponsorOf(e) : null;
|
||||||
|
const ref = sp ? norm(sp.email) : (a.sponsorRef || null);
|
||||||
|
const key = (a.username || '') + '|' + (ref || '');
|
||||||
|
if (s.j !== key) {
|
||||||
|
const r = await call('/v1/join', { email: e, ref: ref || undefined, username: a.username || undefined });
|
||||||
|
if (r.status === 200) {
|
||||||
|
st.stats.joins++;
|
||||||
|
const hubSp = r.body.person && r.body.person.sponsor ? norm(r.body.person.sponsor.email) : null;
|
||||||
|
if (sp && hubSp && hubSp !== norm(sp.email)) noteDisagree(e, hubSp, sp.email, 'join'); // TODO(Marty): hub says earliest join elsewhere
|
||||||
|
} else { st.stats.dropped++; console.log('hubsync join refused', r.status, r.body.error || '', mask(e)); }
|
||||||
|
s.j = key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const w = norm(a.address);
|
||||||
|
if (w && s.w !== w) {
|
||||||
|
const r = await call('/v1/wallet', { email: e, wallet: w });
|
||||||
|
if (r.status === 200) st.stats.wallets++;
|
||||||
|
else { // 404: a waiting copy the hub has not heard of (its own door reports it); 409: the hub holds another wallet
|
||||||
|
st.stats.dropped++; console.log('hubsync wallet refused', r.status, r.body.error || '', mask(e)); }
|
||||||
|
s.w = w;
|
||||||
|
}
|
||||||
|
st.sent[e] = s;
|
||||||
|
}
|
||||||
|
async function flush() {
|
||||||
|
if (!on() || flushing) return { skipped: true };
|
||||||
|
flushing = true; let done = 0, failed = 0;
|
||||||
|
try {
|
||||||
|
const st = load(); const now = Date.now();
|
||||||
|
for (const [e, o] of Object.entries(st.outbox)) {
|
||||||
|
if (o.next > now) continue;
|
||||||
|
try { await report(e); delete st.outbox[e]; done++; }
|
||||||
|
catch (err) { o.tries++; o.next = Date.now() + Math.min(3600000, 30000 * 2 ** Math.min(o.tries, 7)); o.error = String(err.message).slice(0, 120); failed++; st.stats.errors++; }
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
} finally { flushing = false; }
|
||||||
|
return { done, failed };
|
||||||
|
}
|
||||||
|
const tick = () => flush();
|
||||||
|
function adminView() {
|
||||||
|
const st = load();
|
||||||
|
return { on: on(), url: URL_(), site: SITE(), lastSeq: st.lastSeq, outbox: Object.keys(st.outbox).length, stats: st.stats, lastError: st.lastError || null,
|
||||||
|
disagree: Object.entries(st.disagree).slice(-50).map(([e, d]) => ({ member: mask(e), hub: mask(d.hub), here: mask(d.here), how: d.how, at: d.at })), disagreeTotal: Object.keys(st.disagree).length };
|
||||||
|
}
|
||||||
|
module.exports = { init, on, receive, touch, flush, tick, adminView };
|
||||||
+264
@@ -0,0 +1,264 @@
|
|||||||
|
// Launch week (Marty approved 2026-11-05, campaign-2026-11/PLAN.md "Launch-week hook", options B and C).
|
||||||
|
//
|
||||||
|
// FOUNDER BADGE (cosmetic only: no credits, no POL, no perks)
|
||||||
|
// Criterion: the account signed in at least once before the launch moment (siteConfig().launchAt, default
|
||||||
|
// 2026-11-15T06:00:00-06:00, 6 AM Central). "Signed in" = the account's earliest known signed-in visit:
|
||||||
|
// accounts.firstSeen, or lastSeen when firstSeen is not set yet. Both are written only by accounts.touchSeen(),
|
||||||
|
// which runs on signed-in requests (/api/me dashboard load, the /api/my/ping heartbeat, sponsor chat). Since
|
||||||
|
// 2026-11-05 touchSeen keeps firstSeen = the previous lastSeen on the next visit, so a member who signed in before
|
||||||
|
// launch and again after it still reads as "before". Carried-over shell accounts that never signed in have neither
|
||||||
|
// field and never qualify. The flag is stored on the account (accounts.founder = the launch moment, ms).
|
||||||
|
// Grant: automatic from the launch moment (tick every 10 minutes, founderGrant '0' switches it off), idempotent (an
|
||||||
|
// account already flagged is skipped), one run per 10-minute slot across app copies (marks.claim). Admin preview + run
|
||||||
|
// at /api/admin/launch-week. No Telegram posts, no email.
|
||||||
|
//
|
||||||
|
// LAUNCH WEEK CONTEST (option B)
|
||||||
|
// Window [launchContestStart, launchContestEnd): default Sun 2026-11-15 06:00 CT to the end of Sat 2026-11-21 CT
|
||||||
|
// (end stored exclusive as 2026-11-22T00:00:00-06:00). Ranking reuses the weekly leaderboard's count: tier-1 TierPaid
|
||||||
|
// events (the direct sponsor of each package sold), read from the chain index. Never counted: the sponsor's own
|
||||||
|
// positions, any purchase made by a linked position (Qualified Start), the admin account and the company ids
|
||||||
|
// (overrideHouseIds) as contestants or as buyers, and any email or member id in launchContestExcludeEmails /
|
||||||
|
// launchContestExcludeIds (Marty's other accounts). A member must have launchContestMinSales (default 2) counted
|
||||||
|
// sales to place. Ties: more sales, then more dollars, then whoever reached their total first.
|
||||||
|
// Prizes: launchContestPrizesPol (default "10,6,4" = 1st, 2nd, 3rd). Paid ONLY by the admin button after the window
|
||||||
|
// closes (POST /api/admin/launch-week/pay with the exact list the admin saw), through the same payer wallet and the
|
||||||
|
// contract's award(memberId) that the Level 4 override uses. The ranking is frozen on the first pay call; each place
|
||||||
|
// is claimed once (marks.claim) and written to disk as "sending" BEFORE the send, so nothing is ever paid twice.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const TZ = 'America/Chicago';
|
||||||
|
const DEFAULT_LAUNCH = '2026-11-15T06:00:00-06:00';
|
||||||
|
const DEFAULT_END = '2026-11-22T00:00:00-06:00'; // exclusive: the window includes all of Saturday Nov 21, Central
|
||||||
|
const WEI = 10n ** 18n;
|
||||||
|
const GAS_LIMIT = 150000n; // same as the override's award() call
|
||||||
|
|
||||||
|
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
|
||||||
|
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return (s.slice(0, -4) + '.' + s.slice(-4)).replace(/\.?0+$/, ''); };
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
|
const fmtCT = (ts, withTime) => new Date(ts).toLocaleString('en-US', Object.assign({ timeZone: TZ, weekday: 'long', month: 'short', day: 'numeric' }, withTime ? { hour: 'numeric', minute: '2-digit' } : {}));
|
||||||
|
|
||||||
|
function create() {
|
||||||
|
let R = null; // { accounts, chain, marks, leaderboard, payer: () => signer|null, txLink, siteConfig, dataDir, adminEmail, now }
|
||||||
|
const lastError = { at: 0, msg: '' };
|
||||||
|
const now = () => (R && R.now ? R.now() : Date.now());
|
||||||
|
function init(refs) { R = refs; }
|
||||||
|
|
||||||
|
// ---- settings (all date-driven: launch morning needs no deploy) ----
|
||||||
|
function cfg() {
|
||||||
|
const s = R.siteConfig() || {};
|
||||||
|
const t = (v, d) => { const x = Date.parse(String(v || '').trim() || d); return isFinite(x) ? x : Date.parse(d); };
|
||||||
|
const launchAt = t(s.launchAt, DEFAULT_LAUNCH);
|
||||||
|
const start = String(s.launchContestStart || '').trim() ? t(s.launchContestStart, DEFAULT_LAUNCH) : launchAt;
|
||||||
|
const end = t(s.launchContestEnd, DEFAULT_END);
|
||||||
|
const prizes = String(s.launchContestPrizesPol == null || s.launchContestPrizesPol === '' ? '10,6,4' : s.launchContestPrizesPol).split(',').map(x => x.trim()).filter(x => /^\d+(\.\d{1,6})?$/.test(x) && Number(x) > 0);
|
||||||
|
const minSales = Math.max(1, Math.floor(Number(s.launchContestMinSales == null || s.launchContestMinSales === '' ? 2 : s.launchContestMinSales) || 2));
|
||||||
|
const minCents = Math.max(0, Math.floor(Number(s.launchContestMinCents || 0) || 0));
|
||||||
|
const list = v => String(v || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||||
|
const exEmails = new Set(list(s.launchContestExcludeEmails)); if (R.adminEmail) exEmails.add(String(R.adminEmail).toLowerCase());
|
||||||
|
const exIds = new Set([...list(s.overrideHouseIds || '1'), ...list(s.launchContestExcludeIds)].map(Number).filter(Boolean));
|
||||||
|
return { launchAt, start, end, prizes, minSales, minCents, exEmails, exIds,
|
||||||
|
founderGrant: String(s.founderGrant == null ? '1' : s.founderGrant) !== '0',
|
||||||
|
contestOn: String(s.launchContest == null ? '1' : s.launchContest) !== '0' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- FOUNDER ----
|
||||||
|
const earliestSignIn = a => Number(a.firstSeen) || Number(a.lastSeen) || 0;
|
||||||
|
const qualifiesFounder = (a, launchAt) => { const t = earliestSignIn(a); return t > 0 && t < launchAt; };
|
||||||
|
async function founderPreview() {
|
||||||
|
const c = cfg(); const all = await R.accounts.listAll(1e6);
|
||||||
|
const q = all.filter(a => qualifiesFounder(a, c.launchAt));
|
||||||
|
const granted = all.filter(a => a.founder).length;
|
||||||
|
return { launchAt: c.launchAt, launchAtCT: fmtCT(c.launchAt, true), launched: now() >= c.launchAt, field: 'firstSeen (earliest signed-in visit), else lastSeen',
|
||||||
|
accounts: all.length, qualify: q.length, granted, missing: q.filter(a => !a.founder).length, autoGrant: c.founderGrant,
|
||||||
|
neverSignedIn: all.filter(a => !earliestSignIn(a)).length };
|
||||||
|
}
|
||||||
|
// grant the flag to every qualifying account that lacks it. Refuses before the launch moment.
|
||||||
|
async function grantFounders(opts) {
|
||||||
|
const o = opts || {}; const c = cfg();
|
||||||
|
if (now() < c.launchAt) return { error: 'The launch moment (' + fmtCT(c.launchAt, true) + ' Central) has not happened yet. Founder badges are granted from then on.' };
|
||||||
|
const slot = 'lw:founder:' + c.launchAt + ':' + Math.floor(now() / 600000) + (o.manual ? ':m' : '');
|
||||||
|
if (!await R.marks.claim(slot)) return { ok: true, skipped: 'another copy of the app is granting in this slot' };
|
||||||
|
const all = await R.accounts.listAll(1e6); let n = 0;
|
||||||
|
for (const a of all) {
|
||||||
|
if (a.founder || !qualifiesFounder(a, c.launchAt)) continue;
|
||||||
|
try { const r = await R.accounts.setFounder(a.email, c.launchAt); if (r && r.ok && !r.already) n++; } catch (e) { lastError.at = now(); lastError.msg = 'founder ' + a.email + ': ' + e.message; }
|
||||||
|
}
|
||||||
|
if (n) {
|
||||||
|
try { const f = path.join(R.dataDir, 'launchweek', 'founder-grants.json'); fs.mkdirSync(path.dirname(f), { recursive: true }); let log = []; try { log = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} log.push({ at: now(), launchAt: c.launchAt, granted: n, manual: !!o.manual }); fs.writeFileSync(f, JSON.stringify(log.slice(-50))); } catch (e) {}
|
||||||
|
console.log('founder badge: granted to ' + n + ' accounts');
|
||||||
|
}
|
||||||
|
return { ok: true, granted: n };
|
||||||
|
}
|
||||||
|
async function tick() {
|
||||||
|
const c = cfg();
|
||||||
|
if (c.founderGrant && now() >= c.launchAt) {
|
||||||
|
const all = await R.accounts.listAll(1e6);
|
||||||
|
if (all.some(a => !a.founder && qualifiesFounder(a, c.launchAt))) await grantFounders();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// what the member's own badge strip shows: held, or (before launch) on the way
|
||||||
|
function founderState(acct) {
|
||||||
|
const c = cfg(); if (!acct) return { founder: false, pending: false };
|
||||||
|
if (acct.founder) return { founder: true, pending: false };
|
||||||
|
// the caller is the member's own signed-in dashboard request (touchSeen runs in it), so before launch they are on the way
|
||||||
|
return { founder: false, pending: now() < c.launchAt, launchAt: c.launchAt };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- CONTEST: standings ----
|
||||||
|
async function standings(at) {
|
||||||
|
const c = cfg(); const t = at || now();
|
||||||
|
const { map, names, founders, positionIds, mainId } = await R.leaderboard.memberMap();
|
||||||
|
const price = {};
|
||||||
|
const evs = R.chain.recentEvents(1e9);
|
||||||
|
for (const e of evs) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0);
|
||||||
|
const rows = {}; const until = Math.min(c.end, t);
|
||||||
|
for (const e of evs) {
|
||||||
|
if (e.type !== 'TierPaid' || e.tier !== 1 || e.ts < c.start || e.ts >= until) continue;
|
||||||
|
const sponsor = map[e.recipientId], buyer = map[e.buyerId];
|
||||||
|
if (!sponsor) continue;
|
||||||
|
if (buyer && buyer === sponsor) continue; // own positions never count
|
||||||
|
if (positionIds.has(e.buyerId)) continue; // linked positions (Qualified Start) never count
|
||||||
|
if (c.exEmails.has(sponsor) || c.exIds.has(e.recipientId) || c.exIds.has(mainId[sponsor])) continue; // admin, company, Marty's accounts: not contestants
|
||||||
|
if ((buyer && c.exEmails.has(buyer)) || c.exIds.has(e.buyerId)) continue; // company placements / Marty's own buys
|
||||||
|
const cents = price[e.tx + ':' + e.buyerId] || 0;
|
||||||
|
if (cents < c.minCents) continue;
|
||||||
|
const r = rows[sponsor] = rows[sponsor] || { email: sponsor, name: names[sponsor] || 'member', founder: founders.has(sponsor), sales: 0, cents: 0, lastTs: 0, ids: {} };
|
||||||
|
r.sales++; r.cents += cents; r.lastTs = Math.max(r.lastTs, e.ts); r.ids[e.recipientId] = (r.ids[e.recipientId] || 0) + 1;
|
||||||
|
}
|
||||||
|
const list = Object.values(rows).sort((a, b) => b.sales - a.sales || b.cents - a.cents || a.lastTs - b.lastTs || (a.email < b.email ? -1 : 1));
|
||||||
|
list.forEach((r, i) => { r.rank = i + 1; r.usd = r.cents / 100; r.qualifies = r.sales >= c.minSales; r.payId = mainId[r.email] || Number(Object.entries(r.ids).sort((x, y) => y[1] - x[1])[0][0]); });
|
||||||
|
const winners = []; let place = 0;
|
||||||
|
for (const r of list) { if (!r.qualifies || place >= c.prizes.length) continue; winners.push({ place: place + 1, email: r.email, name: r.name, memberId: r.payId, sales: r.sales, usd: r.usd, pol: c.prizes[place] }); place++; }
|
||||||
|
return { start: c.start, end: c.end, open: t < c.end, started: t >= c.start, minSales: c.minSales, prizes: c.prizes, rows: list, winners };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- CONTEST: payout store (one small file per place, single writer per claim) ----
|
||||||
|
const dir = (...p) => path.join(R.dataDir, 'launchweek', 'contest-' + cfg().start, ...p);
|
||||||
|
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
|
||||||
|
const writeJ = (f, o) => { fs.mkdirSync(path.dirname(f), { recursive: true }); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
|
||||||
|
const frozen = () => readJ(dir('frozen.json'));
|
||||||
|
const getPlace = n => readJ(dir('place-' + n + '.json'));
|
||||||
|
const putPlace = (n, patch) => { const o = Object.assign(getPlace(n) || { place: n }, patch, { updated: now() }); writeJ(dir('place-' + n + '.json'), o); return o; };
|
||||||
|
const places = () => { const f = frozen(); return f ? f.winners.map(w => Object.assign({}, w, getPlace(w.place) || { state: 'pending' })) : []; };
|
||||||
|
function txInfo(tx) { // an AwardPaid this contest made: for the email / feed label
|
||||||
|
const h = String(tx || '').toLowerCase(); if (!h || !R) return null;
|
||||||
|
try { for (const p of places()) if (p.txHash && String(p.txHash).toLowerCase() === h) return { place: p.place }; } catch (e) {}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function freeze() {
|
||||||
|
const f = frozen(); if (f) return f;
|
||||||
|
const c = cfg(); if (now() < c.end) return null;
|
||||||
|
if (!await R.marks.claim('lw:freeze:' + c.start)) { for (let i = 0; i < 20 && !frozen(); i++) await new Promise(r => setTimeout(r, 250)); return frozen(); }
|
||||||
|
const s = await standings(c.end);
|
||||||
|
const o = { at: now(), start: c.start, end: c.end, minSales: c.minSales, prizes: c.prizes, winners: s.winners.map(w => Object.assign({}, w, { wei: toWei(w.pol).toString() })), top: s.rows.slice(0, 10).map(r => ({ rank: r.rank, name: r.name, founder: r.founder, sales: r.sales, usd: r.usd, qualifies: r.qualifies })) };
|
||||||
|
writeJ(dir('frozen.json'), o); return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// admin preview: live standings (or the frozen result), what would be paid, the payer and every payout record
|
||||||
|
async function adminView() {
|
||||||
|
const c = cfg(); const s = await standings();
|
||||||
|
const f = frozen(); const p = R.payer ? R.payer() : null;
|
||||||
|
const payer = { keyPresent: !!p };
|
||||||
|
if (p) { payer.address = p.address; try { payer.balancePol = polStr(await p.balance()); } catch (e) { payer.balanceError = e.message; } }
|
||||||
|
return { window: { start: c.start, end: c.end, startCT: fmtCT(c.start, true), endCT: fmtCT(c.end - 1, true), open: s.open, started: s.started },
|
||||||
|
minSales: c.minSales, minCents: c.minCents, prizes: c.prizes, excluded: { emails: [...c.exEmails], ids: [...c.exIds] },
|
||||||
|
standings: s.rows.slice(0, 25).map(r => ({ rank: r.rank, name: r.name, email: r.email, memberId: r.payId, sales: r.sales, usd: r.usd, qualifies: r.qualifies })),
|
||||||
|
wouldPay: (f ? f.winners : s.winners).map(w => ({ place: w.place, name: w.name, email: w.email, memberId: w.memberId, sales: w.sales, pol: w.pol })),
|
||||||
|
frozen: f ? { at: f.at } : null, payouts: places().map(x => ({ place: x.place, name: x.name, memberId: x.memberId, pol: x.pol, state: x.state, txHash: x.txHash || '', tx: x.txHash && R.txLink ? R.txLink(x.txHash) : '', note: x.note || '' })),
|
||||||
|
payer, canPay: !s.open && !!p, founder: await founderPreview(), lastError: lastError.msg ? lastError : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the admin button. `expect` = [{ place, memberId, pol }] exactly as the admin saw it; any difference refuses.
|
||||||
|
async function pay(expect) {
|
||||||
|
const c = cfg();
|
||||||
|
if (now() < c.end) return { error: 'The contest window is still open until ' + fmtCT(c.end - 1, true) + ' Central.' };
|
||||||
|
const p = R.payer ? R.payer() : null; if (!p) return { error: 'No payer wallet: the Level 4 override payer key (OVERRIDE_PAYER_KEY) is not configured.' };
|
||||||
|
const f = await freeze(); if (!f) return { error: 'Could not freeze the results; try again.' };
|
||||||
|
const want = (Array.isArray(expect) ? expect : []).map(x => x.place + ':' + Number(x.memberId) + ':' + String(x.pol)).sort().join('|');
|
||||||
|
const have = f.winners.map(w => w.place + ':' + w.memberId + ':' + w.pol).sort().join('|');
|
||||||
|
if (want !== have) return { error: 'The confirmed list does not match the frozen result. Reload and confirm again.', frozen: f.winners };
|
||||||
|
const todo = f.winners.filter(w => { const s = (getPlace(w.place) || {}).state; return !s || s === 'pending'; });
|
||||||
|
if (!todo.length) return { ok: true, paidNow: 0, payouts: places() };
|
||||||
|
let fees, bal;
|
||||||
|
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { return { error: 'Payer read failed: ' + e.message }; }
|
||||||
|
const total = todo.reduce((n, w) => n + BigInt(w.wei), 0n), gas = BigInt(todo.length) * GAS_LIMIT * BigInt(fees.maxFeePerGas);
|
||||||
|
if (bal < total + gas) return { error: 'Payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; the prizes need ' + polStr(total) + ' POL plus up to ' + polStr(gas) + ' POL gas. Nothing was sent.' };
|
||||||
|
let paidNow = 0;
|
||||||
|
for (const w of todo) {
|
||||||
|
const rec = getPlace(w.place) || {}; const attempt = rec.attempt || 0;
|
||||||
|
if (!await R.marks.claim('lw:pay:' + c.start + ':' + w.place + ':' + attempt)) continue; // another copy (or an earlier click) owns it
|
||||||
|
const cur = getPlace(w.place); if (cur && cur.state && cur.state !== 'pending') continue;
|
||||||
|
putPlace(w.place, Object.assign({}, w, { state: 'checking', attempt }));
|
||||||
|
try { await p.preflight(w.memberId, w.wei); }
|
||||||
|
catch (e) { putPlace(w.place, { state: 'blocked', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent' }); continue; }
|
||||||
|
putPlace(w.place, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
|
||||||
|
let tx;
|
||||||
|
try { tx = await p.send(w.memberId, w.wei, fees); }
|
||||||
|
catch (e) { putPlace(w.place, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
|
||||||
|
putPlace(w.place, { state: 'sent', txHash: tx.hash });
|
||||||
|
console.log('launch contest: place ' + w.place + ' #' + w.memberId + ' ' + w.pol + ' POL tx ' + tx.hash);
|
||||||
|
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putPlace(w.place, { state: 'paid', paidAt: now() }); paidNow++; } else putPlace(w.place, { state: 'failed', note: 'reverted on chain; needs review' }); }
|
||||||
|
catch (e) { putPlace(w.place, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
|
||||||
|
}
|
||||||
|
return { ok: true, paidNow, payouts: places() };
|
||||||
|
}
|
||||||
|
// admin decision on a stuck place: 'paid' with a tx that is an AwardPaid from the payer to that member for that amount,
|
||||||
|
// or 'retry' after checking the payer wallet on the explorer shows nothing went out (blocked / failed / review only)
|
||||||
|
async function resolve(place, action, tx) {
|
||||||
|
const r = getPlace(Number(place)); if (!r) return { error: 'no such place' };
|
||||||
|
if (action === 'paid') {
|
||||||
|
const p = R.payer ? R.payer() : null;
|
||||||
|
const hit = p && R.chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
|
||||||
|
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.wei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + r.pol + ' POL in the chain index' };
|
||||||
|
putPlace(r.place, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return { ok: true };
|
||||||
|
}
|
||||||
|
if (action === 'retry') {
|
||||||
|
const staleSend = r.state === 'sending' && now() - (r.sendingAt || 0) > 15 * 60000; // the app stopped mid-send: you checked the explorer
|
||||||
|
if (!['blocked', 'failed', 'review', 'checking'].includes(r.state) && !staleSend) return { error: 'place is ' + r.state + '; only blocked, failed, review, checking or a send stuck for 15 minutes can be retried' };
|
||||||
|
putPlace(r.place, { state: 'pending', attempt: (r.attempt || 0) + 1, note: 'admin: nothing went out, released for one more try (was ' + r.state + ')' }); return { ok: true };
|
||||||
|
}
|
||||||
|
return { error: 'action must be paid or retry' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- public: the /leaderboard panel (from the launch moment through the payout) ----
|
||||||
|
async function panelState() {
|
||||||
|
const c = cfg(); const t = now();
|
||||||
|
if (!c.contestOn || t < c.start) return null;
|
||||||
|
const f = frozen(); const ps = places();
|
||||||
|
const done = f && (f.winners.length === 0 || ps.every(x => x.state === 'paid'));
|
||||||
|
if (done || t > c.end + 21 * 86400000) return null; // after the payout (or three weeks after the close): gone
|
||||||
|
const s = f ? null : await standings();
|
||||||
|
return { c, s, f, ps };
|
||||||
|
}
|
||||||
|
async function panelHtml() {
|
||||||
|
const st = await panelState(); if (!st) return '';
|
||||||
|
const { c, s, f } = st;
|
||||||
|
const ord = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
|
||||||
|
const prizeLine = c.prizes.map((pol, i) => ord[i] + ' place ' + pol + ' POL').join(' · ');
|
||||||
|
const rows = f ? f.top : s.rows.slice(0, 10).map(r => ({ rank: r.rank, name: r.name, founder: r.founder, sales: r.sales, usd: r.usd, qualifies: r.qualifies }));
|
||||||
|
const open = !f && s.open;
|
||||||
|
let h = '<section class="lwc" id="launch-contest"><p class="eyebrow" style="margin:0 0 4px">Launch week contest</p>'
|
||||||
|
+ '<h2>' + (open ? 'Who is bringing in the most buyers' : 'Final standings') + '</h2>'
|
||||||
|
+ '<p class="muted small" style="margin:0 0 10px">' + esc(fmtCT(c.start, true)) + ' to ' + esc(fmtCT(c.end - 1, true)) + ', Central time. Ranked by packages bought by the people you sponsor directly. '
|
||||||
|
+ 'You need at least ' + c.minSales + ' to place. Your own positions, linked positions and the company account do not count.</p>'
|
||||||
|
+ '<div class="prize"><b>Prizes:</b> ' + esc(prizeLine) + '. Prizes are paid in POL to the wallet on file after the week closes and the results are checked.</div>'
|
||||||
|
+ '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th></tr>'
|
||||||
|
+ (rows.length ? rows.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b>' + (r.founder ? ' <span class="fdr" title="Founder badge">Founder</span>' : '') + (r.qualifies ? '' : ' <span class="muted small">(needs ' + c.minSales + ' to place)</span>') + '</td><td>' + r.sales + '</td><td>$' + Number(r.usd).toLocaleString() + '</td></tr>').join('')
|
||||||
|
: '<tr><td colspan="4" class="muted">No packages sold yet in the contest window. The first sales take the top spots.</td></tr>') + '</table>'
|
||||||
|
+ '<p class="muted small" style="margin:0">' + (open ? 'Standings update live from the chain.' : 'The window is closed. Winners are paid after the results are checked.') + ' No income is guaranteed.</p></section>';
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
// public JSON for /launch and the dashboard
|
||||||
|
async function publicView() {
|
||||||
|
const c = cfg(); const st = await panelState();
|
||||||
|
return { launchAt: c.launchAt, launched: now() >= c.launchAt, contest: { start: c.start, end: c.end, minSales: c.minSales, live: !!st, places: c.prizes.length, prizes: now() >= c.start ? c.prizes : null } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { init, cfg, founderPreview, grantFounders, tick, founderState, qualifiesFounder, standings, freeze, adminView, pay, resolve, panelHtml, publicView, txInfo };
|
||||||
|
}
|
||||||
|
|
||||||
|
const main = create();
|
||||||
|
module.exports = Object.assign(main, { create, DEFAULT_LAUNCH, DEFAULT_END, toWei, polStr });
|
||||||
+18
-13
@@ -38,14 +38,15 @@ function periodBounds(period, ts) {
|
|||||||
let idMap = { at: 0, map: {}, names: {} };
|
let idMap = { at: 0, map: {}, names: {} };
|
||||||
async function memberMap() {
|
async function memberMap() {
|
||||||
if (Date.now() - idMap.at < 60000) return idMap;
|
if (Date.now() - idMap.at < 60000) return idMap;
|
||||||
const map = {}, names = {};
|
const map = {}, names = {}, founders = new Set(), positionIds = new Set(), mainId = {};
|
||||||
const list = await R.accounts.listAll(5000);
|
const list = await R.accounts.listAll(50000);
|
||||||
for (const a of list) {
|
for (const a of list) {
|
||||||
if (a.memberId) { map[a.memberId] = a.email; names[a.email] = a.username ? '@' + a.username : 'member #' + a.memberId; }
|
if (a.memberId) { map[a.memberId] = a.email; mainId[a.email] = a.memberId; names[a.email] = a.username ? '@' + a.username : 'member #' + a.memberId; }
|
||||||
else names[a.email] = a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@';
|
else names[a.email] = a.username ? '@' + a.username : a.email.replace(/@.*/, '') + '@';
|
||||||
try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) map[p.memberId] = a.email; } catch (e) {}
|
if (a.founder) founders.add(a.email); // Founder badge (2026-11-05): shown next to the name on the board
|
||||||
|
try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) { map[p.memberId] = a.email; positionIds.add(p.memberId); } } catch (e) {} // linked positions (Qualified Start)
|
||||||
}
|
}
|
||||||
idMap = { at: Date.now(), map, names }; return idMap;
|
idMap = { at: Date.now(), map, names, founders, positionIds, mainId }; return idMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
const computeCache = {};
|
const computeCache = {};
|
||||||
@@ -55,7 +56,7 @@ async function compute(period) {
|
|||||||
}
|
}
|
||||||
async function computeRaw(period) {
|
async function computeRaw(period) {
|
||||||
const { start, end, label } = periodBounds(period);
|
const { start, end, label } = periodBounds(period);
|
||||||
const { map, names } = await memberMap();
|
const { map, names, founders } = await memberMap();
|
||||||
const price = {}; // tx -> cents
|
const price = {}; // tx -> cents
|
||||||
for (const e of R.chain.recentEvents(1e9)) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0);
|
for (const e of R.chain.recentEvents(1e9)) if (e.type === 'Purchase') price[e.tx + ':' + e.buyerId] = Number(e.priceCents || 0);
|
||||||
const rows = {};
|
const rows = {};
|
||||||
@@ -77,7 +78,7 @@ async function computeRaw(period) {
|
|||||||
for (const [em, n] of Object.entries(joins)) { const r = rows[em] = rows[em] || { email: em, name: names[em] || em, sales: 0, cents: 0, pol: 0n, buyers: new Set() }; r.joins = n; }
|
for (const [em, n] of Object.entries(joins)) { const r = rows[em] = rows[em] || { email: em, name: names[em] || em, sales: 0, cents: 0, pol: 0n, buyers: new Set() }; r.joins = n; }
|
||||||
// the admin's own account (company placements, tank arrivals) is not a contestant
|
// the admin's own account (company placements, tank arrivals) is not a contestant
|
||||||
if (R.adminEmail && rows[R.adminEmail]) delete rows[R.adminEmail];
|
if (R.adminEmail && rows[R.adminEmail]) delete rows[R.adminEmail];
|
||||||
const out = Object.values(rows).map(r => ({ email: r.email, name: r.name, sales: r.sales, usd: r.cents / 100, pol: Number(r.pol / 10n ** 14n) / 10000, buyers: r.buyers.size, joins: r.joins || 0 }))
|
const out = Object.values(rows).map(r => ({ email: r.email, name: r.name, founder: founders.has(r.email), sales: r.sales, usd: r.cents / 100, pol: Number(r.pol / 10n ** 14n) / 10000, buyers: r.buyers.size, joins: r.joins || 0 }))
|
||||||
.sort((a, b) => b.usd - a.usd || b.sales - a.sales || b.joins - a.joins);
|
.sort((a, b) => b.usd - a.usd || b.sales - a.sales || b.joins - a.joins);
|
||||||
out.forEach((r, i) => { r.rank = i + 1; });
|
out.forEach((r, i) => { r.rank = i + 1; });
|
||||||
return { period, label, start, end, rows: out };
|
return { period, label, start, end, rows: out };
|
||||||
@@ -91,7 +92,7 @@ async function view(period, meEmail) {
|
|||||||
return { period: r.period, label: r.label, start: r.start, end: r.end, prize: prize || '', top: r.rows.slice(0, 10).map(pub), me: me ? pub(me) : null, count: r.rows.length,
|
return { period: r.period, label: r.label, start: r.start, end: r.end, prize: prize || '', top: r.rows.slice(0, 10).map(pub), me: me ? pub(me) : null, count: r.rows.length,
|
||||||
winners: winners().slice(0, 6) };
|
winners: winners().slice(0, 6) };
|
||||||
}
|
}
|
||||||
const pub = r => ({ rank: r.rank, name: r.name, sales: r.sales, usd: r.usd, buyers: r.buyers, joins: r.joins });
|
const pub = r => ({ rank: r.rank, name: r.name, founder: !!r.founder, sales: r.sales, usd: r.usd, buyers: r.buyers, joins: r.joins });
|
||||||
// "1000,500,250" -> [1000, 500, 250]: credits for 1st, 2nd, 3rd... (Marty: award the top X positions, 2026-09-14)
|
// "1000,500,250" -> [1000, 500, 250]: credits for 1st, 2nd, 3rd... (Marty: award the top X positions, 2026-09-14)
|
||||||
const ladder = v => String(v || '').split(',').map(x => Math.round(Number(x)) || 0).filter(n => n > 0);
|
const ladder = v => String(v || '').split(',').map(x => Math.round(Number(x)) || 0).filter(n => n > 0);
|
||||||
const ORD = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
|
const ORD = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
|
||||||
@@ -125,24 +126,28 @@ async function rolloverTick() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
|
// the Founder badge next to a name (cosmetic, 2026-11-05)
|
||||||
|
const fdr = r => r && r.founder ? ' <span class="fdr" title="Founder badge: signed in before LinkSpin launched">Founder</span>' : '';
|
||||||
async function renderPage() {
|
async function renderPage() {
|
||||||
const week = await view('week'), month = await view('month'), all = await view('all');
|
const week = await view('week'), month = await view('month'), all = await view('all');
|
||||||
const sc = R.siteConfig();
|
const sc = R.siteConfig();
|
||||||
const table = v => '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th><th>Buyers</th><th>New members</th></tr>'
|
const table = v => '<table class="lb"><tr><th>#</th><th>Member</th><th>Packages</th><th>Sales</th><th>Buyers</th><th>New members</th></tr>'
|
||||||
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b></td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
|
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b>' + fdr(r) + '</td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
|
||||||
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
|
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
|
||||||
const desc = 'Who is selling the most ad packages on LinkSpin this week and this month. Weekly and monthly referral contest standings, read from the chain.';
|
const desc = 'Who is selling the most ad packages on LinkSpin this week and this month. Weekly and monthly referral contest standings, read from the chain.';
|
||||||
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | LinkSpin</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + SITE_URL + '/leaderboard"><meta property="og:title" content="LinkSpin leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="' + SITE_URL + '/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | LinkSpin</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="' + SITE_URL + '/leaderboard"><meta property="og:title" content="LinkSpin leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="' + SITE_URL + '/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
||||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t">'
|
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=ls20261101t">'
|
||||||
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:#ffd15c;font-weight:800}.prize{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
|
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:#ffd15c;font-weight:800}.prize{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}.fdr{display:inline-block;margin-left:6px;padding:1px 7px;border-radius:999px;font-size:11px;font-weight:700;letter-spacing:.04em;color:#7a5600;background:#ffc94d;vertical-align:1px}.lwc{border:1px solid #ffc94d;border-radius:14px;padding:16px 18px;margin:0 0 28px;background:rgba(255,201,77,.07)}.lwc h2{margin:0 0 4px;font-size:24px}.lwc .lb{margin-bottom:8px}</style></head><body><div class="wrap lbw">'
|
||||||
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.</p></section>';
|
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.</p></section>';
|
||||||
|
if (R.launchPanel) { try { h += await R.launchPanel(); } catch (e) { console.error('launch panel', e.message); } } // launch week contest (launchweek.js), date-driven
|
||||||
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
|
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
|
||||||
h += '<h2 style="font-size:24px;margin:0 0 4px">' + month.label + '</h2>' + (month.prize ? '<div class="prize"><b>Monthly prizes:</b> ' + esc(month.prize) + '</div>' : '') + table(month);
|
h += '<h2 style="font-size:24px;margin:0 0 4px">' + month.label + '</h2>' + (month.prize ? '<div class="prize"><b>Monthly prizes:</b> ' + esc(month.prize) + '</div>' : '') + table(month);
|
||||||
h += '<h2 style="font-size:24px;margin:0 0 4px">All time</h2>' + table(all);
|
h += '<h2 style="font-size:24px;margin:0 0 4px">All time</h2>' + table(all);
|
||||||
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. Weekly and monthly prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261101t"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261113nl"></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 };
|
function setLaunchPanel(fn) { if (R) R.launchPanel = fn; }
|
||||||
|
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds, memberMap, setLaunchPanel, ctParts };
|
||||||
|
|||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
// Network conversions (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: nothing here touches sponsors, payouts, credits or
|
||||||
|
// the chain. InstantAdPay reports sign-ups, wallet links and package purchases by accounts that arrived on a LinkSpin click
|
||||||
|
// (op 'events' on /api/partner/conv, signed); LinkSpin counts them for the click's owner.
|
||||||
|
//
|
||||||
|
// - The ledger is DATA_DIR/netconv.jsonl: append-only, one write per event, so the two app copies of a deploy can both add
|
||||||
|
// to it without rewriting each other (unlike the JSON stores that rewrite the whole file). Each copy re-reads it when its
|
||||||
|
// size changes.
|
||||||
|
// - Once: marks.claim is true for exactly one copy; a key already in the ledger is a dup, so a repeat after marks are pruned
|
||||||
|
// is still refused. join and wallet count once per ROOT click (an ad click and the spin click it led to are one click), and
|
||||||
|
// each purchase counts by its own key (tx + log index). A click belongs to the first account seen on it.
|
||||||
|
// - Window: convtrack's rule, 30 days from the real click to the EVENT (not to delivery, so a retry queue never loses one).
|
||||||
|
// - The click owner's own account, and own clicks, are kept as tests: in the ledger with self:1, never counted, no postback.
|
||||||
|
// - Each row carries what the click was, so a later event still counts after the hit aged out of the rotator.
|
||||||
|
// - Spin-link events are mirrored into rotator.conv (per-link counts, sources, Reports) and Banner Spin events into its
|
||||||
|
// own conv; the mirror is replayed from the ledger on a timer, so a copy that lost a write during a deploy heals.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const EVENTS = ['join', 'wallet', 'purchase'];
|
||||||
|
let FILE = null, C = null, R = null, B = null, P = null, M = null;
|
||||||
|
let st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() };
|
||||||
|
const norm = e => String(e || '').trim().toLowerCase();
|
||||||
|
const DAY = 86400000;
|
||||||
|
const acctHash = email => crypto.createHash('sha256').update('netconv|' + norm(email)).digest('hex').slice(0, 16); // never the address itself
|
||||||
|
|
||||||
|
function init(o) {
|
||||||
|
FILE = path.join(o.dataDir, 'netconv.jsonl'); C = o.convtrack; R = o.rotator; B = o.bannerspin || null; P = o.postbacks || null; M = o.marks;
|
||||||
|
st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; refresh();
|
||||||
|
if (!o.noTimers) { setTimeout(() => syncMirror().catch(() => {}), 30000).unref(); setInterval(() => syncMirror().catch(() => {}), 300000).unref(); }
|
||||||
|
}
|
||||||
|
function refresh() {
|
||||||
|
let size = 0; try { size = fs.statSync(FILE).size; } catch (e) {}
|
||||||
|
if (size === st.size) return st;
|
||||||
|
const n = { size, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() };
|
||||||
|
let raw = ''; try { raw = fs.readFileSync(FILE, 'utf8'); } catch (e) {}
|
||||||
|
for (const line of raw.split('\n')) {
|
||||||
|
if (!line) continue; let r; try { r = JSON.parse(line); } catch (e) { continue; }
|
||||||
|
n.rows.push(r); n.keys.add(String(r.k).split('|')[0]);
|
||||||
|
for (const [m, id] of [[n.byClick, r.click], [n.byRoot, r.root]]) { const a = m.get(id); if (a) a.push(r); else m.set(id, [r]); }
|
||||||
|
}
|
||||||
|
st = n; return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the facts of a click, for one owner, as they stand now
|
||||||
|
function factsOf(L, o) {
|
||||||
|
const sp = L.spin, ad = L.ad, bs = L.bspin, mineSpin = !!(sp && sp.owner === o), mineAd = !!(ad && ad.owner === o);
|
||||||
|
return { kind: mineSpin ? 'spin' : (mineAd ? ad.k : (bs ? 'bspin' : (ad ? ad.k : 'spin'))),
|
||||||
|
camp: mineAd ? ad.camp : undefined, cname: mineAd ? ad.cname : undefined,
|
||||||
|
rot: mineSpin ? sp.rotation.id : undefined, rcode: mineSpin ? sp.rotation.code : undefined, rname: mineSpin ? sp.rotation.name : undefined, d: mineSpin ? sp.hit.d : undefined, sr: mineSpin ? (sp.hit.sr || undefined) : undefined,
|
||||||
|
bcode: bs ? bs.spin.code : undefined, src: (sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : ''))) || '', c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.dv : ad && ad.dv)) || '',
|
||||||
|
q: (sp ? sp.hit.q : (bs ? bs.click.q : undefined)) || undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
// e: { k, ev, click, email, value, ts, tx, sk }. Returns { result }: counted | self | dup | other | expired | nomatch | bad.
|
||||||
|
// Every one of those is final: the sender stops retrying on any answer.
|
||||||
|
async function record(e) {
|
||||||
|
const ev = String(e && e.ev || ''), k = String(e && e.k || '').slice(0, 120), click = String(e && e.click || ''); const email = norm(e && e.email);
|
||||||
|
if (!EVENTS.includes(ev) || !k || !C.isClickId(click) || !email || email.length > 190) return { result: 'bad' };
|
||||||
|
let S = refresh(); if (S.keys.has(k)) return { result: 'dup' };
|
||||||
|
const now = Date.now(); const at = Math.min(Number(e.ts) || now, now);
|
||||||
|
const L = C.lookup(click); const prior = S.byClick.get(click) || null;
|
||||||
|
if (!L && !prior) return { result: 'nomatch' };
|
||||||
|
const root = prior ? prior[0].root : L.root; const clickTs = prior ? prior[0].clickTs : L.ts;
|
||||||
|
if (at - clickTs > C.WINDOW_MS) return { result: 'expired' };
|
||||||
|
const acct = acctHash(email); const seen = S.byRoot.get(root) || [];
|
||||||
|
if (seen.length && seen[0].acct !== acct) return { result: 'other' }; // one click, one person: the first account on it
|
||||||
|
if (ev !== 'purchase' && seen.some(r => r.ev === ev)) return { result: 'dup' };
|
||||||
|
if (!(await M.claim('net:' + (ev === 'purchase' ? k : root + ':' + ev)))) return { result: 'dup' };
|
||||||
|
const owners = L ? [...new Set(L.owners)] : [...new Set((prior || []).map(r => r.owner))];
|
||||||
|
const value = ev === 'purchase' ? C.cleanValue(e.value) : 0;
|
||||||
|
const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : '';
|
||||||
|
const tx = String(e.tx || '').slice(0, 80) || undefined;
|
||||||
|
const rows = owners.map(o => {
|
||||||
|
const was = (prior || []).find(r => r.owner === o);
|
||||||
|
const f = L ? factsOf(L, o) : { kind: was.kind, camp: was.camp, cname: was.cname, rot: was.rot, rcode: was.rcode, rname: was.rname, d: was.d, sr: was.sr, bcode: was.bcode, src: was.src, c: was.c, dv: was.dv, q: was.q };
|
||||||
|
const self = email === o || !!(was && was.self) || seen.some(r => r.owner === o && r.self) || (L ? C.selfFor(L, o, sk) : false);
|
||||||
|
const row = Object.assign({ k: owners.length > 1 ? k + '|' + o : k, ev, ts: at, rec: now, value, acct, click, root, clickTs, owner: o, tx, self: self ? 1 : undefined }, f);
|
||||||
|
for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x];
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
fs.appendFileSync(FILE, rows.map(r => JSON.stringify(r) + '\n').join('')); // one write: the whole event lands or none of it
|
||||||
|
refresh();
|
||||||
|
let counted = false;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (r.self) continue;
|
||||||
|
counted = true;
|
||||||
|
await mirror(r).catch(err => console.error('netconv mirror', err.message));
|
||||||
|
if (P) P.fire(r.owner, ev, { q: r.q || {}, source: r.src, country: r.c, device: r.dv, lsid: click, code: r.rcode || r.bcode || '', sourceId: r.sr || '', payout: value, currency: 'USD', txid: tx || '', label: ev }).catch(err => console.error('netconv postback', err.message));
|
||||||
|
}
|
||||||
|
return { result: counted ? 'counted' : 'self' };
|
||||||
|
}
|
||||||
|
// LinkSpin's own sign-ups, wallets and purchases that arrived on an ad click (a / i ids): the rotator cannot see those clicks
|
||||||
|
async function fromLinkSpin(lsid, ev, facts) {
|
||||||
|
const f = facts || {}; if (!EVENTS.includes(ev) || f.key || !f.email) return null;
|
||||||
|
const k = 'ls:' + ev + ':' + (ev === 'purchase' ? (f.txid || crypto.randomBytes(6).toString('hex')) : acctHash(f.email));
|
||||||
|
await record({ k, ev, click: lsid, email: f.email, value: f.payout, ts: Date.now(), tx: f.txid });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
async function mirror(r) {
|
||||||
|
const key = r.k.split('|')[0];
|
||||||
|
if (r.rot) return R.convert(r.click, r.ev, { payout: r.value, label: r.ev === 'purchase' ? 'InstantAdPay' : undefined, key, ts: r.ts, bound: { r: r.rot, d: r.d, sr: r.sr } });
|
||||||
|
if (r.kind === 'bspin' && r.click[0] === 'k') return R.convert(r.click, r.ev, { payout: r.value, key, ts: r.ts });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
async function syncMirror() { for (const r of refresh().rows) if (!r.self && r.rot) await mirror(r).catch(() => {}); }
|
||||||
|
|
||||||
|
const mineSince = (o, since) => refresh().rows.filter(r => r.owner === o && r.ts >= since);
|
||||||
|
const ORDER = ['join', 'lead', 'wallet', 'purchase', 'external'];
|
||||||
|
// Reports > Conversions: everything once. Rows mirrored into the rotator are read from the rotator (which also holds
|
||||||
|
// LinkSpin's own joins, wallets, purchases, leads and partner postbacks), the ledger adds only what the rotator cannot
|
||||||
|
// hold (ad clicks, Banner Spin clicks), Banner Spin's own rows add its site events, goals come from the pixel.
|
||||||
|
function unified(owner, days) {
|
||||||
|
const o = norm(owner); const since = Date.now() - Math.max(1, Number(days) || 30) * DAY;
|
||||||
|
const m = {}; const buyers = new Set();
|
||||||
|
const add = (k, v) => { const x = m[k] = m[k] || { k, n: 0, value: 0 }; x.n++; x.value += Number(v) || 0; };
|
||||||
|
for (const c of R.convRows(o, since)) { add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); }
|
||||||
|
if (B && B.convRows) for (const c of B.convRows(o, since)) { if (c.key) continue; add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); }
|
||||||
|
for (const r of mineSince(o, since)) { if (r.self || r.rot) continue; add(r.ev, r.value); if (r.ev === 'purchase') buyers.add(r.root); }
|
||||||
|
const goals = {}; for (const c of C.goalRowsOf(o, since)) { const g = goals[c.goal] = goals[c.goal] || { k: 'goal:' + c.goal, n: 0, value: 0 }; g.n++; g.value += c.value || 0; }
|
||||||
|
const rows = ORDER.filter(k => m[k]).map(k => m[k]).concat(Object.keys(m).filter(k => !ORDER.includes(k)).map(k => m[k]), Object.values(goals).sort((a, b) => b.n - a.n)).map(x => Object.assign(x, { value: Math.round(x.value * 100) / 100 }));
|
||||||
|
return { rows, joins: (m.join || {}).n || 0, wallets: (m.wallet || {}).n || 0, purchases: (m.purchase || {}).n || 0, buyers: buyers.size, goals: Object.values(goals).reduce((n, g) => n + g.n, 0) };
|
||||||
|
}
|
||||||
|
// InstantAdPay's Campaigns card: the same rows, and the events on each of the member's InstantAdPay ad campaigns
|
||||||
|
function partner(owner, days) {
|
||||||
|
const o = norm(owner); const d = Math.max(1, Math.min(90, Number(days) || 30)); const since = Date.now() - d * DAY;
|
||||||
|
const byCampaign = {};
|
||||||
|
for (const r of mineSince(o, since)) { if (r.self || r.kind !== 'iap' || !r.camp) continue; const b = byCampaign[r.camp] = byCampaign[r.camp] || { join: 0, wallet: 0, purchase: 0, value: 0 }; b[r.ev]++; b.value = Math.round((b.value + (r.value || 0)) * 100) / 100; }
|
||||||
|
const selfEvents = mineSince(o, since).filter(r => r.self).length;
|
||||||
|
return { rows: unified(o, d).rows, byCampaign, selfEvents, days: d };
|
||||||
|
}
|
||||||
|
function adminCounts() { const a = refresh().rows; return { rows: a.length, counted: a.filter(r => !r.self).length }; }
|
||||||
|
module.exports = { init, record, fromLinkSpin, unified, partner, syncMirror, adminCounts, EVENTS };
|
||||||
+212
@@ -0,0 +1,212 @@
|
|||||||
|
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
|
||||||
|
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
|
||||||
|
//
|
||||||
|
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||||
|
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||||
|
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
||||||
|
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||||
|
// P mints a token bound to R, the state and the email, and sends the browser
|
||||||
|
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||||
|
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
|
||||||
|
// (so nobody can push their own token into someone else's browser), and spends
|
||||||
|
// the nonce (a second use is refused). The email must already be a member
|
||||||
|
// here; then R makes an ordinary session and redirects to the relative path.
|
||||||
|
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||||
|
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||||
|
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||||
|
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||||
|
// bots and non-page fetches never bounce.
|
||||||
|
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||||
|
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||||
|
//
|
||||||
|
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
|
||||||
|
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
|
||||||
|
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||||
|
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||||
|
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||||
|
const enabled = () => SECRET().length >= 32;
|
||||||
|
const TTL = 60 * 1000; // token life
|
||||||
|
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||||
|
const STATE_AGE = 300; // seconds: the state cookie
|
||||||
|
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
||||||
|
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||||
|
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||||
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners' };
|
||||||
|
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||||
|
|
||||||
|
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||||
|
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
|
||||||
|
|
||||||
|
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
|
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||||
|
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
|
||||||
|
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||||
|
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
|
||||||
|
|
||||||
|
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
|
||||||
|
function safePath(to, dflt) {
|
||||||
|
const d = dflt == null ? '/' : dflt;
|
||||||
|
const s = String(to == null ? '' : to);
|
||||||
|
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
|
||||||
|
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function mint(o) {
|
||||||
|
const now = o.now || Date.now();
|
||||||
|
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||||
|
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||||
|
if (o.name) t.name = String(o.name).slice(0, 40);
|
||||||
|
const body = b64u(JSON.stringify(t));
|
||||||
|
return 'v1.' + body + '.' + b64u(mac(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
// -> { ok, email, to, n, exp } or { error: reason }
|
||||||
|
function verify(tok, o) {
|
||||||
|
if (!enabled()) return { error: 'off' };
|
||||||
|
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||||
|
if (!m) return { error: 'malformed' };
|
||||||
|
const want = mac(m[1]), got = unb64u(m[2]);
|
||||||
|
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||||
|
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||||
|
const now = (o && o.now) || Date.now();
|
||||||
|
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
|
||||||
|
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||||
|
const st = String((o && o.st) || '');
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||||
|
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||||
|
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||||
|
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||||
|
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||||
|
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||||
|
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
|
||||||
|
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
|
||||||
|
function loadFile() {
|
||||||
|
if (fileLoaded) return; fileLoaded = true;
|
||||||
|
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
|
||||||
|
}
|
||||||
|
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
|
||||||
|
async function spend(n, exp) {
|
||||||
|
const now = Date.now(); loadFile(); prune(now);
|
||||||
|
if (used.has(n)) return false;
|
||||||
|
used.set(n, Number(exp) + SKEW); saveFile();
|
||||||
|
const db = C && C.db;
|
||||||
|
if (db && db.enabled && db.enabled()) {
|
||||||
|
try {
|
||||||
|
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
|
||||||
|
await tableReady;
|
||||||
|
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
|
||||||
|
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
|
||||||
|
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// crawlers, link previews and headless browsers never bounce
|
||||||
|
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
|
||||||
|
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
|
||||||
|
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
|
||||||
|
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
|
||||||
|
|
||||||
|
function cookies(req) {
|
||||||
|
const out = {};
|
||||||
|
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
|
||||||
|
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||||
|
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||||
|
|
||||||
|
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
|
||||||
|
|
||||||
|
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||||
|
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||||
|
|
||||||
|
// -> true when the request was one of ours and has been answered
|
||||||
|
async function handle(req, res, u) {
|
||||||
|
if (!C || req.method !== 'GET') return false;
|
||||||
|
const p = u.pathname;
|
||||||
|
const peerName = NAMES[C.peer] || C.peer;
|
||||||
|
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||||
|
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||||
|
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||||
|
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||||
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const plain = base + to;
|
||||||
|
if (!enabled() || isBot(req)) return go(res, plain);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) return go(res, plain);
|
||||||
|
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
|
||||||
|
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
|
||||||
|
}
|
||||||
|
if (p === '/sso/start') {
|
||||||
|
const to = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||||
|
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||||
|
const via = String(u.searchParams.get('via') || '');
|
||||||
|
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||||
|
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||||
|
const c = cookies(req);
|
||||||
|
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||||
|
const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
const set = [ck('nsso.st', st, STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||||
|
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to), set);
|
||||||
|
}
|
||||||
|
if (p === '/sso/check') {
|
||||||
|
const st = String(u.searchParams.get('st') || '');
|
||||||
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const r = String(u.searchParams.get('r') || '');
|
||||||
|
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||||
|
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
||||||
|
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||||
|
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) { log('check: not signed in here', null, 'for ' + forName); return go(res, none); }
|
||||||
|
let w = null;
|
||||||
|
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||||
|
log('token issued', s.email, 'for ' + forName);
|
||||||
|
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||||
|
}
|
||||||
|
if (p === '/sso/in') {
|
||||||
|
const c = cookies(req);
|
||||||
|
const set = [ck('nsso.st', '', 0, true)];
|
||||||
|
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
||||||
|
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||||
|
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||||
|
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
|
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||||
|
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
|
||||||
|
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
|
||||||
|
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
|
||||||
|
return go(res, C.signinPath(v.to), set);
|
||||||
|
}
|
||||||
|
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
||||||
|
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
|
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
|
||||||
|
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||||
|
}
|
||||||
|
if (p === '/api/sso/status') {
|
||||||
|
const c = cookies(req); const set = [];
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
const signedIn = !!(s && (s.email || s.address));
|
||||||
|
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||||
|
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||||
|
return sendJson(res, out, set);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, handle, enabled, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||||
+5
-1
@@ -344,7 +344,11 @@ function create() {
|
|||||||
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
|
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
|
// the same payer wallet + award(memberId) path for other admin-approved POL awards (launch contest, 2026-11-05):
|
||||||
|
// null when no key is configured. Independent of overrideMode: the caller is an admin button, not the weekly scheduler.
|
||||||
|
const payerHandle = () => (payerOverride || keyHex()) ? payer() : null;
|
||||||
|
const polygonTx = h => txLink(h);
|
||||||
|
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg, payerHandle, polygonTx };
|
||||||
}
|
}
|
||||||
|
|
||||||
const main = create();
|
const main = create();
|
||||||
|
|||||||
@@ -172,6 +172,12 @@ async function write(owner, id, body) {
|
|||||||
return { ok: true, page: pub(p), by };
|
return { ok: true, page: pub(p), by };
|
||||||
}
|
}
|
||||||
function totals() { return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, leads: J.db.leads.length }; }
|
function totals() { return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, leads: J.db.leads.length }; }
|
||||||
|
// site-wide figures for the daily snapshot: page views, leads and new pages inside the `since` window
|
||||||
|
function window24(since) {
|
||||||
|
const views = J.db.views.filter(v => v.ts >= since && (v.k || 'view') === 'view');
|
||||||
|
return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, created: J.db.pages.filter(p => (p.created || 0) >= since).length,
|
||||||
|
views: views.length, unique: new Set(views.map(v => v.v)).size, leads: J.db.leads.filter(l => l.ts >= since).length };
|
||||||
|
}
|
||||||
// -- Reports (2026-10-10): the member's page views, uniques, clicks-through and leads for the last N days, by Central day and by page
|
// -- Reports (2026-10-10): the member's page views, uniques, clicks-through and leads for the last N days, by Central day and by page
|
||||||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||||
async function summary(owner, days) {
|
async function summary(owner, days) {
|
||||||
@@ -263,4 +269,4 @@ function adminAll() {
|
|||||||
formProvider: p.type === 'squeeze' && c.formEmbed ? formrestyle.provider(c.formEmbed) : null, views: o.views, uniques: o.u.size, clicks: o.clicks, leads: ld[p.id] || 0 }; });
|
formProvider: p.type === 'squeeze' && c.formEmbed ? formrestyle.provider(c.formEmbed) : null, views: o.views, uniques: o.u.size, clicks: o.clicks, leads: ld[p.id] || 0 }; });
|
||||||
}
|
}
|
||||||
function adminImages() { return J.db.images.map(i => Object.assign(pubImage(i), { owner: i.owner })); }
|
function adminImages() { return J.db.images.map(i => Object.assign(pubImage(i), { owner: i.owner })); }
|
||||||
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider, adminAll, adminImages };
|
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, window24, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider, adminAll, adminImages };
|
||||||
|
|||||||
+1
-1
@@ -133,7 +133,7 @@ async function test(owner, id) {
|
|||||||
// a conversion happened for an account: find the click that brought them, record it on the rotator, fire the owner's postbacks
|
// a conversion happened for an account: find the click that brought them, record it on the rotator, fire the owner's postbacks
|
||||||
async function convertFor(email, event, facts) {
|
async function convertFor(email, event, facts) {
|
||||||
const c = clickOf(email); if (!c) return null;
|
const c = clickOf(email); if (!c) return null;
|
||||||
const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, facts || {}) : null;
|
const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, Object.assign({}, facts || {}, { email: norm(email) })) : null;
|
||||||
if (!hit) return null;
|
if (!hit) return null;
|
||||||
const ctx = Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: c.lsid, code: hit.code, sourceId: hit.sourceId || '' }, facts || {});
|
const ctx = Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: c.lsid, code: hit.code, sourceId: hit.sourceId || '' }, facts || {});
|
||||||
try { await fire(hit.owner, event, ctx); } catch (e) {}
|
try { await fire(hit.owner, event, ctx); } catch (e) {}
|
||||||
|
|||||||
+10
-2
@@ -485,6 +485,14 @@
|
|||||||
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
|
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
|
||||||
<div id="ovOut" class="small"></div>
|
<div id="ovOut" class="small"></div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card" id="lwCard">
|
||||||
|
<div class="card-head"><h3>Launch week</h3><span class="sub">Founder badge (cosmetic) and the launch week contest (POL prizes, paid only from this button)</span></div>
|
||||||
|
<p class="small" id="lwFounder">…</p>
|
||||||
|
<p class="small" id="lwWindow"></p>
|
||||||
|
<div id="lwStand" class="small"></div>
|
||||||
|
<div id="lwPayouts" class="small"></div>
|
||||||
|
<p><button class="btn small sec" type="button" id="lwRefresh">Refresh</button> <button class="btn small sec" type="button" id="lwGrant" hidden>Grant Founder badges now</button> <button class="btn small" type="button" id="lwPay" hidden>Pay launch contest</button></p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pane" id="pane-settings" hidden>
|
<div class="pane" id="pane-settings" hidden>
|
||||||
<div class="card" id="kitCard">
|
<div class="card" id="kitCard">
|
||||||
@@ -540,8 +548,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></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=20261101t"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
|
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script><script src="/assets/admin-launchweek.js?v=20261105lw"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+4
-4
@@ -75,9 +75,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/ads-screen.js?v=20261027nr"></script>
|
<script src="/assets/ads-screen.js?v=20261113sso"></script>
|
||||||
<script src="/assets/fuel.js?v=20261025ff"></script>
|
<script src="/assets/fuel.js?v=20261113sso"></script>
|
||||||
<script src="/assets/engine-room.js?v=20261101t"></script>
|
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// Admin > Launch week (2026-11-05): Founder badge preview + grant, launch contest standings and the "Pay launch contest" button.
|
||||||
|
// The pay button sends real POL from the Level 4 override payer wallet. It shows the frozen ranking and amounts first and
|
||||||
|
// sends exactly that list; the server refuses if anything changed, and every place is paid at most once.
|
||||||
|
(function () {
|
||||||
|
const $ = IAP.$;
|
||||||
|
if (!$('lwCard')) return;
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
async function api(path, body) {
|
||||||
|
const r = await (await fetch(path, body === undefined ? { cache: 'no-store' } : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).json();
|
||||||
|
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
let last = null;
|
||||||
|
async function load() {
|
||||||
|
let r; try { r = await api('/api/admin/launch-week'); } catch (e) { $('lwFounder').textContent = 'Could not read launch week: ' + e.message; return; }
|
||||||
|
last = r;
|
||||||
|
const f = r.founder || {};
|
||||||
|
$('lwFounder').innerHTML = '<b>Founder badge</b> (cosmetic): accounts whose earliest signed-in visit (' + esc(f.field) + ') is before ' + esc(f.launchAtCT) + ' Central. '
|
||||||
|
+ '<b>' + (f.qualify || 0) + '</b> qualify today of ' + (f.accounts || 0) + ' accounts (' + (f.neverSignedIn || 0) + ' never signed in). Granted: ' + (f.granted || 0) + ', still to grant: ' + (f.missing || 0) + '. '
|
||||||
|
+ (f.launched ? 'Launch has passed; the automatic grant runs every 10 minutes' : 'The automatic grant starts at the launch moment') + (f.autoGrant ? '.' : ' (switched OFF: founderGrant = 0).');
|
||||||
|
$('lwGrant').hidden = !f.launched;
|
||||||
|
const w = r.window || {};
|
||||||
|
$('lwWindow').innerHTML = '<b>Launch week contest</b>: ' + esc(w.startCT) + ' to ' + esc(w.endCT) + ' Central · ' + (w.open ? (w.started ? 'OPEN' : 'not started') : 'CLOSED')
|
||||||
|
+ ' · minimum ' + r.minSales + ' sales to place · prizes ' + (r.prizes || []).map((p, i) => (i + 1) + ': ' + p + ' POL').join(', ')
|
||||||
|
+ ' · excluded: ' + esc((r.excluded.emails || []).join(', ')) + ' and member #' + esc((r.excluded.ids || []).join(', #'))
|
||||||
|
+ ' · payer ' + (r.payer.keyPresent ? esc(r.payer.address) + ' holds ' + esc(r.payer.balancePol || '?') + ' POL' : 'NOT configured');
|
||||||
|
$('lwStand').innerHTML = (r.standings || []).length ? '<table><tr><th>#</th><th>Member</th><th>Pays to</th><th>Sales</th><th>$</th><th>Places?</th></tr>' + r.standings.map(x => '<tr><td>' + x.rank + '</td><td>' + esc(x.name) + ' <span class="muted">' + esc(x.email) + '</span></td><td>#' + x.memberId + '</td><td>' + x.sales + '</td><td>$' + x.usd + '</td><td>' + (x.qualifies ? 'yes' : 'no') + '</td></tr>').join('') + '</table>' : '<p class="muted">No counted sales in the window yet.</p>';
|
||||||
|
$('lwPayouts').innerHTML = (r.payouts || []).length ? '<p><b>Payout records</b> (frozen ' + new Date(r.frozen.at).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT)</p><table><tr><th>Place</th><th>Member</th><th>POL</th><th>State</th><th>Tx</th></tr>' + r.payouts.map(x => '<tr><td>' + x.place + '</td><td>' + esc(x.name) + ' #' + x.memberId + '</td><td>' + esc(x.pol) + '</td><td>' + esc(x.state) + (x.note ? ' <span class="muted">' + esc(x.note) + '</span>' : '') + '</td><td>' + (x.tx ? '<a href="' + esc(x.tx) + '" target="_blank" rel="noopener">tx</a>' : '') + '</td></tr>').join('') + '</table>' : '';
|
||||||
|
$('lwPay').hidden = !r.canPay || !(r.wouldPay || []).length || (r.payouts || []).length && r.payouts.every(x => x.state === 'paid');
|
||||||
|
}
|
||||||
|
$('lwRefresh').addEventListener('click', load);
|
||||||
|
$('lwGrant').addEventListener('click', async () => {
|
||||||
|
try { const r = await api('/api/admin/launch-week/founders', {}); IAP.status('Founder badge: granted to ' + (r.granted || 0) + ' accounts' + (r.skipped ? ' (' + r.skipped + ')' : '') + '.', 'ok'); load(); } catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
|
});
|
||||||
|
$('lwPay').addEventListener('click', async () => {
|
||||||
|
await load(); if (!last) return;
|
||||||
|
const list = last.wouldPay || []; if (!list.length) { IAP.status('Nobody placed: nothing to pay.', 'bad'); return; }
|
||||||
|
const total = list.reduce((n, x) => n + Number(x.pol), 0);
|
||||||
|
const text = list.map(x => 'Place ' + x.place + ': ' + x.name + ' (member #' + x.memberId + ', ' + x.sales + ' sales) gets ' + x.pol + ' POL').join('\n') + '\n\nTotal ' + total + ' POL plus gas, sent from the payer wallet with award(memberId). Each place is paid once.';
|
||||||
|
if (!await IAP.confirmBox(text, { title: 'Pay the launch week contest?', ok: 'Pay ' + total + ' POL', cancel: 'Cancel' })) return;
|
||||||
|
try { const r = await api('/api/admin/launch-week/pay', { confirm: true, places: list.map(x => ({ place: x.place, memberId: x.memberId, pol: x.pol })) }); IAP.status('Launch contest: ' + (r.paidNow || 0) + ' paid now.', 'ok'); load(); } catch (e) { IAP.status(e.message, 'bad'); load(); }
|
||||||
|
});
|
||||||
|
load();
|
||||||
|
})();
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||||
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||||
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit' };
|
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit', invited: 'the member named who invited them' };
|
||||||
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
|
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||||
function side(f) {
|
function side(f) {
|
||||||
if (!f) return '<span class="muted">no account</span>';
|
if (!f) return '<span class="muted">no account</span>';
|
||||||
|
|||||||
@@ -300,10 +300,10 @@
|
|||||||
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members: the free activation is held ' + (r.holdHours || 24) + ' h (a purchase never is), then auto-assigned in rotation';
|
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members: the free activation is held ' + (r.holdHours || 24) + ' h (a purchase never is), then auto-assigned in rotation';
|
||||||
// ready = wallet linked: the plain activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
|
// ready = wallet linked: the plain 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.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>')
|
$('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>')
|
||||||
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (InstantAdPay) 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 (InstantAdPay) 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' ? '' : 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) {}
|
||||||
}
|
}
|
||||||
async function loadMembers() {
|
async function loadMembers() {
|
||||||
@@ -514,7 +514,7 @@
|
|||||||
$('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; }));
|
$('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; }));
|
||||||
$('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); }));
|
$('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); }));
|
||||||
$('updSend').addEventListener('click', busy($('updSend'), async () => {
|
$('updSend').addEventListener('click', busy($('updSend'), async () => {
|
||||||
const inp = updInput(); if (!inp.noteIds.length) { IAP.status('Pick at least one note.', 'bad'); return; }
|
const inp = updInput(); if (!inp.noteIds.length && !String(inp.intro || '').trim()) { IAP.status('Write an intro or pick at least one note.', 'bad'); return; }
|
||||||
const opt = $('updAudience').selectedOptions[0].textContent;
|
const opt = $('updAudience').selectedOptions[0].textContent;
|
||||||
if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return;
|
if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return;
|
||||||
const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates();
|
const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates();
|
||||||
@@ -1038,7 +1038,8 @@
|
|||||||
loginCreditsPerDay: ['Login ad: legacy credits per day', 'only for old login ads with no end date (none since slots)'],
|
loginCreditsPerDay: ['Login ad: legacy credits per day', 'only for old login ads with no end date (none since slots)'],
|
||||||
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)', 'partner-network (NAS) views and member ads in other members zones cost 1/N of the on-site rate; 1 = same rate; whole numbers'],
|
synRateDivisor: ['Network rate divisor (N)', 'partner-network (NAS) banner views and member banners in other members zones cost 1/N of the on-site rate; 1 = same rate; whole numbers'],
|
||||||
|
synRateDivisorText: ['Network rate divisor for TEXT ads (N)', 'off-site text-ad views cost 1/N of the on-site text rate (10 = 1 credit per 100 network views); whole numbers'],
|
||||||
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
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'],
|
||||||
@@ -1092,7 +1093,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', 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: 'Daily growth snapshot: targets (feed = proof channel, 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)', 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)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' };
|
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', 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: 'Daily growth snapshot: targets (feed = proof channel, support = LinkSpin Support topic, echo = shared payments topic; comma list)', telegramSupportChatId: 'Telegram LinkSpin Support topic: chat id', telegramSupportTopicId: 'Telegram LinkSpin Support topic: topic id', 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)', 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)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' };
|
||||||
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>'
|
||||||
|
|||||||
@@ -23,9 +23,10 @@
|
|||||||
const cs = D.campaigns || []; const live = cs.filter(c => c.status === 'active');
|
const cs = D.campaigns || []; const live = cs.filter(c => c.status === 'active');
|
||||||
{ const sel = $('fAud'); if (sel) { const keep = sel.value; sel.innerHTML = '<option value="">Everyone</option>' + (D.audiences || []).map(a => '<option value="' + a.id + '">' + esc(a.name) + ' (' + fmt(a.size30) + ')</option>').join(''); sel.value = keep; sel.onchange = () => { $('fAudModeRow').hidden = !sel.value; }; } }
|
{ const sel = $('fAud'); if (sel) { const keep = sel.value; sel.innerHTML = '<option value="">Everyone</option>' + (D.audiences || []).map(a => '<option value="' + a.id + '">' + esc(a.name) + ' (' + fmt(a.size30) + ')</option>').join(''); sel.value = keep; sel.onchange = () => { $('fAudModeRow').hidden = !sel.value; }; } }
|
||||||
const views = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0) + (c.impsSyn || 0), 0);
|
const views = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0) + (c.impsSyn || 0), 0);
|
||||||
const synN = Math.max(1, Math.floor(Number(D.rates && D.rates.synRateDivisor) || 1)); // network rate (Marty, 2026-10-27, 4:1)
|
const synN0 = Math.max(1, Math.floor(Number(D.rates && D.rates.synRateDivisor) || 1)); // network rate (Marty, 2026-10-27, 4:1)
|
||||||
const offTxt = c => (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : '')
|
const synT = Math.max(1, Math.floor(Number(D.rates && D.rates.synRateDivisorText != null ? D.rates.synRateDivisorText : synN0) || 1)); // text ads (Marty, 2026-11-12, 1/10)
|
||||||
+ (c.impsSyn ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsSyn) + ' partner zones' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : '');
|
const offTxt = c => { const synN = c.type === 'text' ? synT : synN0; return (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : '')
|
||||||
|
+ (c.impsSyn ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsSyn) + ' partner zones' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : ''); };
|
||||||
CR.sub(live.length + ' live · ' + fmt(D.availableCredits) + ' credits available');
|
CR.sub(live.length + ' live · ' + fmt(D.availableCredits) + ' credits available');
|
||||||
const hours = new Array(24).fill(0); Object.values(D.hours || {}).forEach(a => (a || []).forEach((n, i) => { hours[i] += Number(n) || 0; })); // last 7 days by UTC hour, all campaigns
|
const hours = new Array(24).fill(0); Object.values(D.hours || {}).forEach(a => (a || []).forEach((n, i) => { hours[i] += Number(n) || 0; })); // last 7 days by UTC hour, all campaigns
|
||||||
const week = hours.reduce((a, b) => a + b, 0);
|
const week = hours.reduce((a, b) => a + b, 0);
|
||||||
@@ -35,7 +36,7 @@
|
|||||||
CR.tile({ k: 'Views delivered', v: fmt(views), series: week ? hours : null, note: week ? fmt(week) + ' in 7 days, by hour' : '' }),
|
CR.tile({ k: 'Views delivered', v: fmt(views), series: week ? hours : null, note: week ? fmt(week) + ' in 7 days, by hour' : '' }),
|
||||||
CR.tile({ k: 'Today\'s viewing', v: EARN.views + ' / ' + EARN.target, note: EARN.streakDay > 1 ? 'streak day ' + EARN.streakDay : '' })].join('');
|
CR.tile({ k: 'Today\'s viewing', v: EARN.views + ' / ' + EARN.target, note: EARN.streakDay > 1 ? 'streak day ' + EARN.streakDay : '' })].join('');
|
||||||
const r = D.rates || {};
|
const r = D.rates || {};
|
||||||
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views' + (synN > 1 ? ' here (views on the partner network and in other members\u2019 zones cost 1/' + synN + ' of that)' : '') + ', ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day login slot (' + (slotInfo().free ? slotInfo().free + ' of ' + slotInfo().max + ' open' : 'all ' + slotInfo().max + ' taken' + (slotInfo().queued ? ', ' + slotInfo().queued + ' in line' : '') + ', reserve the next one') + '). Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
|
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views' + (synN0 > 1 ? ' here (views on the partner network and in other members\u2019 zones cost 1/' + synN0 + ' of that for banners' + (synT !== synN0 ? ', 1/' + synT + ' for text ads' : '') + ')' : '') + ', ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day login slot (' + (slotInfo().free ? slotInfo().free + ' of ' + slotInfo().max + ' open' : 'all ' + slotInfo().max + ' taken' + (slotInfo().queued ? ', ' + slotInfo().queued + ' in line' : '') + ', reserve the next one') + '). Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
|
||||||
// traffic-light status (2026-10-20): live green, running low amber (80%+ of the budget spent), out red, paused grey
|
// traffic-light status (2026-10-20): live green, running low amber (80%+ of the budget spent), out red, paused grey
|
||||||
const stKey = c => c.status === 'queued' ? 'queued' : c.status === 'cancelled' ? 'cancelled' : c.scheduled ? 'sched' : c.status === 'active' ? (c.type !== 'login' && c.budget > 0 && c.spent / c.budget >= 0.8 ? 'low' : 'live') : c.status === 'paused' ? 'paused' : c.status === 'out' ? 'out' : c.status === 'done' ? 'ended' : '';
|
const stKey = c => c.status === 'queued' ? 'queued' : c.status === 'cancelled' ? 'cancelled' : c.scheduled ? 'sched' : c.status === 'active' ? (c.type !== 'login' && c.budget > 0 && c.spent / c.budget >= 0.8 ? 'low' : 'live') : c.status === 'paused' ? 'paused' : c.status === 'out' ? 'out' : c.status === 'done' ? 'ended' : '';
|
||||||
const ST_LABEL = { queued: 'In line', cancelled: 'Cancelled, refunded', sched: 'Scheduled', live: 'Live', low: 'Running low', paused: 'Paused', out: 'Out of credits', ended: 'Ended' };
|
const ST_LABEL = { queued: 'In line', cancelled: 'Cancelled, refunded', sched: 'Scheduled', live: 'Live', low: 'Running low', paused: 'Paused', out: 'Out of credits', ended: 'Ended' };
|
||||||
@@ -50,7 +51,7 @@
|
|||||||
+ (!['done', 'cancelled'].includes(c.status) ? '<button class="btn sm" type="button" data-edit="' + c.id + '" title="' + (c.edits ? 'Edit the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (' + fmt(D.editFee) + ' credits)' : 'Fix the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (first edit free)') + '">Edit</button>' : '') + '</span></div>').join('')
|
+ (!['done', 'cancelled'].includes(c.status) ? '<button class="btn sm" type="button" data-edit="' + c.id + '" title="' + (c.edits ? 'Edit the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (' + fmt(D.editFee) + ' credits)' : 'Fix the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (first edit free)') + '">Edit</button>' : '') + '</span></div>').join('')
|
||||||
: '<div class="rw"><span class="muted">No ads yet. Launch one: a banner, a text ad or a login-ad slot.</span></div>';
|
: '<div class="rw"><span class="muted">No ads yet. Launch one: a banner, a text ad or a login-ad slot.</span></div>';
|
||||||
if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '<div class="muted" style="margin-top:8px">Your welcome credits unlock after the short welcome tour on <a href="/tools">the classic dashboard</a>.</div>');
|
if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '<div class="muted" style="margin-top:8px">Your welcome credits unlock after the short welcome tour on <a href="/tools">the classic dashboard</a>.</div>');
|
||||||
$('foot').textContent = 'views = views here on LinkSpin; network = the partner ad network; partner zones = other members\u2019 zones on their own sites' + (synN > 1 ? ' (network and partner-zone views cost 1/' + synN + ' of the rate here, so ' + synN + ' of them cost what 1 view here does)' : '') + ' · a paused ad keeps its credits · unspent credits return when an ad ends';
|
$('foot').textContent = 'views = views here on LinkSpin; network = the partner ad network; partner zones = other members\u2019 zones on their own sites' + (synN0 > 1 ? ' (network and partner-zone views cost 1/' + synN0 + ' of the rate here, so ' + synN0 + ' of them cost what 1 view here does' + (synT !== synN0 ? '; text ads 1/' + synT : '') + ')' : '') + ' · a paused ad keeps its credits · unspent credits return when an ad ends';
|
||||||
$('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause')));
|
$('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause')));
|
||||||
$('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume')));
|
$('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume')));
|
||||||
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => { const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return; try { await api('/api/my/campaigns/' + b.dataset.top + '/topup', { credits: Number(v.credits) }); toast('Topped up.'); load(); } catch (e) { toast(e.message, true); } }));
|
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => { const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return; try { await api('/api/my/campaigns/' + b.dataset.top + '/topup', { credits: Number(v.credits) }); toast('Topped up.'); load(); } catch (e) { toast(e.message, true); } }));
|
||||||
@@ -133,13 +134,21 @@
|
|||||||
if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; }
|
if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; }
|
||||||
$('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : '';
|
$('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : '';
|
||||||
cost(); preview(); }
|
cost(); preview(); }
|
||||||
|
// a login slot is paid from ONE position (2026-11-04): say what each position has free and stop the buy up front when none covers it
|
||||||
|
const loginShort = () => { const F = D && D.loginFunds; return !!(F && F.best < slotInfo().credits); };
|
||||||
|
function fundsLine() { const F = D && D.loginFunds; if (!F) return ''; const L = slotInfo();
|
||||||
|
const per = (F.per || []).length > 1 ? ' (' + F.per.map(x => '#' + x.memberId + ': ' + fmt(x.avail)).join(', ') + ')' : '';
|
||||||
|
return '<span style="display:block;line-height:1.7;margin-top:4px' + (loginShort() ? ';color:var(--bad,#c0392b)' : '') + '">Paid from one position. '
|
||||||
|
+ (loginShort() ? 'None of yours has <b>' + fmt(L.credits) + '</b> purchased credits free on its own' + per + '. Buy a package on one position to bring it to ' + fmt(L.credits) + ', then come back.'
|
||||||
|
: 'Your best-funded position has <b>' + fmt(F.best) + '</b> purchased credits free' + per + '.') + '</span>'; }
|
||||||
|
function fundsGate() { if (TYPE !== 'login') return; const b = $('fGo'); b.disabled = loginShort(); if (loginShort()) b.title = 'No single position has ' + fmt(slotInfo().credits) + ' purchased credits free'; }
|
||||||
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full, reserve the next)'); }
|
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full, reserve the next)'); }
|
||||||
function cost() { const b = Math.floor(Number($('fBudget').value) || 0); const r = D ? D.rates : {}; let s = '';
|
function cost() { const b = Math.floor(Number($('fBudget').value) || 0); const r = D ? D.rates : {}; let s = '';
|
||||||
if (TYPE === 'banner') s = 'about ' + fmt(Math.floor(b / (r.bannerCreditsPerBatch || 2) * (r.bannerBatch || 10))) + ' timed views';
|
if (TYPE === 'banner') s = 'about ' + fmt(Math.floor(b / (r.bannerCreditsPerBatch || 2) * (r.bannerBatch || 10))) + ' timed views';
|
||||||
else if (TYPE === 'text') s = 'about ' + fmt(Math.floor(b / (r.textCreditsPerBatch || 1) * (r.textBatch || 10))) + ' timed views';
|
else if (TYPE === 'text') s = 'about ' + fmt(Math.floor(b / (r.textCreditsPerBatch || 1) * (r.textBatch || 10))) + ' timed views';
|
||||||
else { const L = slotInfo(); $('fCost').innerHTML = L.free
|
else { const L = slotInfo(); $('fCost').innerHTML = (L.free
|
||||||
? '<b>' + fmt(L.credits) + '</b> purchased credits for <b>' + L.days + '</b> days of unlimited sign-in impressions · <b>' + L.free + '</b> of ' + L.max + ' slots open'
|
? '<b>' + fmt(L.credits) + '</b> purchased credits for <b>' + L.days + '</b> days of unlimited sign-in impressions · <b>' + L.free + '</b> of ' + L.max + ' slots open'
|
||||||
: '<span style="display:block;line-height:1.7">All <b>' + L.max + '</b> login-ad slots are taken' + (L.queued ? ', <b>' + L.queued + '</b> paid reservation' + (L.queued === 1 ? '' : 's') + ' in line' : '') + '. Reserve the next one: <b>' + fmt(L.credits) + '</b> purchased credits now and you would be <b>#' + nextPlace().place + '</b> in line. ' + esc(estText(nextPlace().estStartCt)) + ' Cancel before it starts for a full refund.</span>'; return; }
|
: '<span style="display:block;line-height:1.7">All <b>' + L.max + '</b> login-ad slots are taken' + (L.queued ? ', <b>' + L.queued + '</b> paid reservation' + (L.queued === 1 ? '' : 's') + ' in line' : '') + '. Reserve the next one: <b>' + fmt(L.credits) + '</b> purchased credits now and you would be <b>#' + nextPlace().place + '</b> in line. ' + esc(estText(nextPlace().estStartCt)) + ' Cancel before it starts for a full refund.</span>') + fundsLine(); fundsGate(); return; }
|
||||||
$('fCost').innerHTML = b >= 10 ? s.replace(/(about )([\d,]+)/, '$1<b>$2</b>') : 'minimum <b>10</b> credits'; }
|
$('fCost').innerHTML = b >= 10 ? s.replace(/(about )([\d,]+)/, '$1<b>$2</b>') : 'minimum <b>10</b> credits'; }
|
||||||
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><img src="' + esc(IMG) + '" alt="" style="max-width:100%;width:' + sz[0] + 'px;height:auto;border:1px solid var(--chrome-line);background:var(--inset)">'; }
|
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><img src="' + esc(IMG) + '" alt="" style="max-width:100%;width:' + sz[0] + 'px;height:auto;border:1px solid var(--chrome-line);background:var(--inset)">'; }
|
||||||
else if (TYPE === 'text') p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><div class="panel" style="max-width:420px"><b>' + esc($('fTitle').value || 'Your headline') + '</b><br><span class="ink2">' + esc($('fBody').value || 'One line under it.') + '</span><br><span class="mono muted" style="font-size:11px">' + esc(host($('fTarget').value || 'yoursite.com')) + '</span></div>';
|
else if (TYPE === 'text') p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><div class="panel" style="max-width:420px"><b>' + esc($('fTitle').value || 'Your headline') + '</b><br><span class="ink2">' + esc($('fBody').value || 'One line under it.') + '</span><br><span class="mono muted" style="font-size:11px">' + esc(host($('fTarget').value || 'yoursite.com')) + '</span></div>';
|
||||||
@@ -172,7 +181,10 @@
|
|||||||
$('fGo').disabled = true;
|
$('fGo').disabled = true;
|
||||||
try { const r = await api('/api/my/campaigns', body); const c = r.campaign || {};
|
try { const r = await api('/api/my/campaigns', body); const c = r.campaign || {};
|
||||||
toast(c.status === 'queued' ? 'Reserved and paid. You are #' + (c.place || '?') + ' in line. We let you know when it starts.' : TYPE === 'login' ? 'Launched. Your login-ad slot runs for ' + slotInfo().days + ' days.' : 'Launched. It is live in rotation now.');
|
toast(c.status === 'queued' ? 'Reserved and paid. You are #' + (c.place || '?') + ' in line. We let you know when it starts.' : TYPE === 'login' ? 'Launched. Your login-ad slot runs for ' + slotInfo().days + ' days.' : 'Launched. It is live in rotation now.');
|
||||||
$('composer').hidden = true; $('fName').value = ''; load(); } catch (e) { toast(e.message, true); } finally { $('fGo').disabled = false; }
|
$('composer').hidden = true; $('fName').value = ''; load(); } catch (e) {
|
||||||
|
// a login-ad failure stays on screen until read (the 2-second toast was missed, 2026-11-03)
|
||||||
|
if (TYPE === 'login') await dialog({ title: body.reserve ? 'Your reservation did not go through' : 'Your login ad did not launch', text: e.message, ok: 'OK', no: 'Close' }); else toast(e.message, true);
|
||||||
|
} finally { $('fGo').disabled = false; fundsGate(); }
|
||||||
});
|
});
|
||||||
CR.requireSession(load);
|
CR.requireSession(load);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -65,6 +65,10 @@
|
|||||||
$('bsHoursChip').textContent = LSHours.chip(s.hours, s.tz); $('bsHoursChip').classList.toggle('set', !!s.hours);
|
$('bsHoursChip').textContent = LSHours.chip(s.hours, s.tz); $('bsHoursChip').classList.toggle('set', !!s.hours);
|
||||||
$('bsOffNote').hidden = !s.adminOff; if (s.adminOff) $('bsOffNote').textContent = 'LinkSpin took this Banner Spin offline' + (s.adminNote ? ' (' + s.adminNote + ')' : '') + '. Placements show a blank image and clicks go to the fallback. Ask on Help if you think this is a mistake.';
|
$('bsOffNote').hidden = !s.adminOff; if (s.adminOff) $('bsOffNote').textContent = 'LinkSpin took this Banner Spin offline' + (s.adminNote ? ' (' + s.adminNote + ')' : '') + '. Placements show a blank image and clicks go to the fallback. Ask on Help if you think this is a mistake.';
|
||||||
renderTiles(s, STATS[id]); renderBanners(s); renderSettings(s); renderCodes(s); renderAddLimit(s);
|
renderTiles(s, STATS[id]); renderBanners(s); renderSettings(s); renderCodes(s); renderAddLimit(s);
|
||||||
|
// the Add a banner frame follows the selected spin's size (Marty 11-05: it kept the first spin's 728x90); a pick made
|
||||||
|
// for another spin is dropped so it is never checked or uploaded against the wrong size
|
||||||
|
if (PEND && PEND.spin !== id) { PEND = null; $('bsFile').value = ''; $('bsImgUrl').value = ''; }
|
||||||
|
if (!PEND) preview($('bsPrev'), s, null);
|
||||||
if (!quiet) window.scrollTo({ top: 0 });
|
if (!quiet) window.scrollTo({ top: 0 });
|
||||||
loadStats(id);
|
loadStats(id);
|
||||||
}
|
}
|
||||||
@@ -151,8 +155,8 @@
|
|||||||
if (r.error) throw new Error(r.error); return r;
|
if (r.error) throw new Error(r.error); return r;
|
||||||
}
|
}
|
||||||
// add a banner: upload first when a file is chosen, then save
|
// add a banner: upload first when a file is chosen, then save
|
||||||
$('bsFile').addEventListener('change', () => { const s = cur(); if (!s) return; $('bsImgUrl').value = ''; PEND = PEND || {}; pickFile($('bsFile'), $('bsPrev'), s, PEND); });
|
$('bsFile').addEventListener('change', () => { const s = cur(); if (!s) return; $('bsImgUrl').value = ''; PEND = PEND || {}; PEND.spin = s.id; pickFile($('bsFile'), $('bsPrev'), s, PEND); });
|
||||||
$('bsImgUrl').addEventListener('change', async () => { const s = cur(); if (!s) return; $('bsFile').value = ''; PEND = { url: $('bsImgUrl').value.trim() }; PEND.d = await preview($('bsPrev'), s, PEND.url || null); PEND.ok = !!PEND.d; });
|
$('bsImgUrl').addEventListener('change', async () => { const s = cur(); if (!s) return; $('bsFile').value = ''; PEND = { url: $('bsImgUrl').value.trim(), spin: s.id }; PEND.d = await preview($('bsPrev'), s, PEND.url || null); PEND.ok = !!PEND.d; });
|
||||||
$('bsTgtKind').addEventListener('change', () => { $('bsTgtUrlWrap').hidden = $('bsTgtKind').value !== 'url'; });
|
$('bsTgtKind').addEventListener('change', () => { $('bsTgtUrlWrap').hidden = $('bsTgtKind').value !== 'url'; });
|
||||||
$('bsAddBtn').addEventListener('click', async () => {
|
$('bsAddBtn').addEventListener('click', async () => {
|
||||||
const s = cur(); if (!s) return; const P = PEND || {};
|
const s = cur(); if (!s) return; const P = PEND || {};
|
||||||
|
|||||||
+17
-2
@@ -198,8 +198,8 @@ window.IAP = (function () {
|
|||||||
{ key: 'wallet', title: 'Link your wallet', done: !!m.address, href: '/wallet', cta: 'Wallet',
|
{ key: 'wallet', title: 'Link your wallet', done: !!m.address, href: '/wallet', cta: 'Wallet',
|
||||||
how: 'Wallet tab, Connect, sign the free message. MetaMask recommended. Never held crypto? The wallet guide in Training walks through buying POL with a card.',
|
how: 'Wallet tab, Connect, sign the free message. MetaMask recommended. Never held crypto? The wallet guide in Training walks through buying POL with a card.',
|
||||||
why: 'Payouts go to this address. No wallet, nowhere to pay you.' },
|
why: 'Payouts go to this address. No wallet, nowhere to pay you.' },
|
||||||
{ key: 'payouts', title: 'Switch on payouts', done: !!m.memberId, href: '/wallet', cta: 'Wallet',
|
{ key: 'payouts', title: 'Payouts switched on', done: !!m.memberId, href: '/wallet', cta: 'Wallet',
|
||||||
how: 'Wallet tab, one small transaction. It registers your address with the contract.',
|
how: 'Happens by itself once your wallet is linked and you have a sponsor: LinkSpin registers your address on the contract and pays the gas. Joined with no sponsor? Tell us who invited you, or you wait in the holding tank while one is matched (up to 24 hours after you link your wallet).',
|
||||||
why: 'The contract binds each buyer to their sponsor at their first purchase. If payouts are off when your first person buys, that commission is not yours.' },
|
why: 'The contract binds each buyer to their sponsor at their first purchase. If payouts are off when your first person buys, that commission is not yours.' },
|
||||||
{ key: 'level2', title: 'Qualify: open level 2', done: bc >= 2, href: '/credits', cta: 'Buy packages',
|
{ key: 'level2', title: 'Qualify: open level 2', done: bc >= 2, href: '/credits', cta: 'Buy packages',
|
||||||
how: 'Two of your people buy a $25 or more package. Or use Qualified Start: add two positions from extra wallets in your own MetaMask and buy a $25 package from each (about $23 of POL in each wallet).',
|
how: 'Two of your people buy a $25 or more package. Or use Qualified Start: add two positions from extra wallets in your own MetaMask and buy a $25 package from each (about $23 of POL in each wallet).',
|
||||||
@@ -251,3 +251,18 @@ window.IAP = (function () {
|
|||||||
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $,
|
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $,
|
||||||
guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by /support and the chat hand-off
|
guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by /support and the chat hand-off
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// Network links (2026-11-13): a click on a link to InstantAdPay goes through /go/iap, which signs a signed-in member in over there and is a
|
||||||
|
// plain redirect for everyone else. Rewritten at click time only, so links people copy to share stay clean. data-nogo opts a link out.
|
||||||
|
(function () {
|
||||||
|
if (window.__netlinks) return; window.__netlinks = 1;
|
||||||
|
const HOSTS = ['instantadpay.com', 'www.instantadpay.com'];
|
||||||
|
document.addEventListener('click', e => {
|
||||||
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||||
|
const a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
|
||||||
|
if (!a || a.hasAttribute('download') || a.hasAttribute('data-nogo')) return;
|
||||||
|
let u; try { u = new URL(a.href); } catch (x) { return; }
|
||||||
|
if (u.protocol !== 'https:' || !HOSTS.includes(u.hostname)) return;
|
||||||
|
a.href = '/go/iap?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
||||||
|
}, true);
|
||||||
|
})();
|
||||||
|
|||||||
@@ -4,6 +4,10 @@
|
|||||||
// <div id="page">, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
|
// <div id="page">, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
|
||||||
window.CR = (function () {
|
window.CR = (function () {
|
||||||
const $ = id => document.getElementById(id);
|
const $ = id => document.getElementById(id);
|
||||||
|
// network sign-in (2026-11-12): signed in on InstantAdPay = signed in here, no code (netsso.js asks the server once; same file on both sites)
|
||||||
|
try { if (!document.querySelector('script[src^="/assets/netsso.js"]')) { const ns = document.createElement('script'); ns.src = '/assets/netsso.js?v=20261112sso'; ns.async = true; document.head.appendChild(ns); } } catch (e) {}
|
||||||
|
// launch day is 2026-11-15 Central: the pre-launch notice shows only before it
|
||||||
|
function prelaunch() { try { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < '2026-11-15'; } catch (e) { return false; } }
|
||||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
const fmt = n => Number(n || 0).toLocaleString();
|
const fmt = n => Number(n || 0).toLocaleString();
|
||||||
const NAV = [
|
const NAV = [
|
||||||
@@ -17,17 +21,19 @@ window.CR = (function () {
|
|||||||
['reports', 'Reports', '/reports', '<path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/>'],
|
['reports', 'Reports', '/reports', '<path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/>'],
|
||||||
['conversions', 'Conversions', '/conversions', '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="0.8"/>'], // conversion pixel goals (2026-10-23)
|
['conversions', 'Conversions', '/conversions', '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="4"/><circle cx="12" cy="12" r="0.8"/>'], // conversion pixel goals (2026-10-23)
|
||||||
['team', 'Team', '/team', '<circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/>'],
|
['team', 'Team', '/team', '<circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/>'],
|
||||||
|
['tank', 'Holding tank', '/tools#line', '<path d="M4 9h16l-1.5 10h-13z"/><path d="M7 9V7a5 5 0 0 1 10 0v2"/><path d="M9.5 14h5"/>'], // adopters only (2026-11-11): shown by tankItem()
|
||||||
['wallet', 'Wallet', '/wallet', '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/>'],
|
['wallet', 'Wallet', '/wallet', '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/>'],
|
||||||
['promo', 'Promo tools', '/tools#promo', '<path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/>'],
|
['promo', 'Promo tools', '/tools#promo', '<path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/>'],
|
||||||
['training', 'Training', '/tools#training', '<rect x="3" y="5" width="18" height="13" rx="2"/><path d="M10 9l5 2.5-5 2.5z"/>', 1],
|
['training', 'Training', '/tools#training', '<rect x="3" y="5" width="18" height="13" rx="2"/><path d="M10 9l5 2.5-5 2.5z"/>', 1],
|
||||||
['pipeline', 'Pipeline', '/tools#pipeline', '<rect x="3" y="5" width="5" height="14" rx="1"/><rect x="9.5" y="5" width="5" height="10" rx="1"/><rect x="16" y="5" width="5" height="7" rx="1"/>', 1],
|
['pipeline', 'Pipeline', '/tools#pipeline', '<rect x="3" y="5" width="5" height="14" rx="1"/><rect x="9.5" y="5" width="5" height="10" rx="1"/><rect x="16" y="5" width="5" height="7" rx="1"/>', 1],
|
||||||
['profile', 'Profile', '/tools#profile', '<circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-4 3-6 7-6s7 2 7 6"/>', 1],
|
['profile', 'Profile', '/tools#profile', '<circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-4 3-6 7-6s7 2 7 6"/>', 1],
|
||||||
|
['forum', 'Earners Corner', 'https://earnerscorner.com/session/sso', '<path d="M4 5.5h16v10H9l-5 4z"/><path d="M8 9.5h8M8 13h5"/>'], // the network forum (2026-11-10), signs in with InstantAdPay
|
||||||
['help', 'Help', '/help', '<circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.2-2.4 3.7"/><path d="M12 17h.01"/>'],
|
['help', 'Help', '/help', '<circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.2-2.4 3.7"/><path d="M12 17h.01"/>'],
|
||||||
['tools', 'More', '/tools', '<circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/>'],
|
['tools', 'More', '/tools', '<circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/>'],
|
||||||
];
|
];
|
||||||
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
|
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
|
||||||
const FALLBACK = {}; // the classic /my dashboard is retired (2026-10-08); its leftover panes live at /tools
|
const FALLBACK = {}; // the classic /my dashboard is retired (2026-10-08); its leftover panes live at /tools
|
||||||
const BUILT = new Set(['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'refuel', 'reports', 'conversions', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile', 'help']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11); Help = support tickets (2026-10-16)
|
const BUILT = new Set(['tank', 'forum', 'links', 'sources', 'pages', 'zones', 'ads', 'credits', 'refuel', 'reports', 'conversions', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile', 'help']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11); Help = support tickets (2026-10-16)
|
||||||
let ME = null, toastT;
|
let ME = null, toastT;
|
||||||
// Deep links (2026-10-25): /credits#refuel, /credits#buy and /ads#engine scroll to their panel once it has loaded (and any
|
// Deep links (2026-10-25): /credits#refuel, /credits#buy and /ads#engine scroll to their panel once it has loaded (and any
|
||||||
// sign-in or sponsor pop-up is closed) and flash it, so a button that says "Refuel" lands ON the Refuel panel.
|
// sign-in or sponsor pop-up is closed) and flash it, so a button that says "Refuel" lands ON the Refuel panel.
|
||||||
@@ -62,7 +68,7 @@ window.CR = (function () {
|
|||||||
if (!ARR || $('crArrive')) return '';
|
if (!ARR || $('crArrive')) return '';
|
||||||
if (!document.getElementById('crArriveCss')) { const st = document.createElement('style'); st.id = 'crArriveCss'; st.textContent = '.arrive{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:12px 24px 0;padding:10px 14px;border:1px solid var(--sig,#ff6a1a);border-radius:8px;background:var(--sig-soft,#FFF8F2);font-size:13.5px;line-height:1.45}.arrive .grow{flex:1 1 auto}.arrive button{border:0;background:none;font-size:18px;line-height:1;cursor:pointer;color:inherit;padding:0 2px}@media (max-width:900px){.arrive{margin:10px 16px 0}}.cr-flash{animation:crFlash 2.4s ease-out 1}@keyframes crFlash{0%,40%{box-shadow:0 0 0 4px rgba(255,106,26,.55)}100%{box-shadow:0 0 0 0 rgba(255,106,26,0)}}'; document.head.appendChild(st); }
|
if (!document.getElementById('crArriveCss')) { const st = document.createElement('style'); st.id = 'crArriveCss'; st.textContent = '.arrive{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:12px 24px 0;padding:10px 14px;border:1px solid var(--sig,#ff6a1a);border-radius:8px;background:var(--sig-soft,#FFF8F2);font-size:13.5px;line-height:1.45}.arrive .grow{flex:1 1 auto}.arrive button{border:0;background:none;font-size:18px;line-height:1;cursor:pointer;color:inherit;padding:0 2px}@media (max-width:900px){.arrive{margin:10px 16px 0}}.cr-flash{animation:crFlash 2.4s ease-out 1}@keyframes crFlash{0%,40%{box-shadow:0 0 0 4px rgba(255,106,26,.55)}100%{box-shadow:0 0 0 0 rgba(255,106,26,0)}}'; document.head.appendChild(st); }
|
||||||
return '<div class="arrive" id="crArrive" role="note"><span><b>You came from InstantAdPay to ' + esc(ARR[0]) + '.</b> <span id="crArriveSi">Sign in with the same email you use on InstantAdPay, then </span><b>Step 1:</b> ' + esc(ARR[1])
|
return '<div class="arrive" id="crArrive" role="note"><span><b>You came from InstantAdPay to ' + esc(ARR[0]) + '.</b> <span id="crArriveSi">Sign in with the same email you use on InstantAdPay, then </span><b>Step 1:</b> ' + esc(ARR[1])
|
||||||
+ (ARR[2] ? ' <a href="' + ARR[2] + '" target="_blank" rel="noopener">' + esc(ARR[3]) + '</a>' : '') + '</span><span class="grow"></span><a href="https://instantadpay.com/my#engine">Back to InstantAdPay</a><button type="button" aria-label="Hide this note" id="crArriveX">×</button></div>';
|
+ (ARR[2] ? ' <a href="' + ARR[2] + '" target="_blank" rel="noopener">' + esc(ARR[3]) + '</a>' : '') + '</span><span class="grow"></span><a href="/go/iap?to=%2Fmy%23engine">Back to InstantAdPay</a><button type="button" aria-label="Hide this note" id="crArriveX">×</button></div>';
|
||||||
}
|
}
|
||||||
// Expired session (Marty 2026-10-23: "told me to sign in but never redirected me"): sessions last 24 h, and a screen
|
// Expired session (Marty 2026-10-23: "told me to sign in but never redirected me"): sessions last 24 h, and a screen
|
||||||
// left open past that got 'Sign in first.' errors with no way forward. Any 401 from our API, or coming back to a tab
|
// left open past that got 'Sign in first.' errors with no way forward. Any 401 from our API, or coming back to a tab
|
||||||
@@ -105,11 +111,11 @@ window.CR = (function () {
|
|||||||
const act = railActive(o);
|
const act = railActive(o);
|
||||||
const app = document.createElement('div'); app.className = 'app'; let railWide = true; try { railWide = localStorage.getItem('cr.rail') !== 'narrow'; } catch (e) {} if (railWide) app.classList.add('wide'); // expanded by default (Marty 2026-10-08), the choice remembered per browser
|
const app = document.createElement('div'); app.className = 'app'; let railWide = true; try { railWide = localStorage.getItem('cr.rail') !== 'narrow'; } catch (e) {} if (railWide) app.classList.add('wide'); // expanded by default (Marty 2026-10-08), the choice remembered per browser
|
||||||
app.innerHTML = '<nav class="rail" aria-label="LinkSpin"><a class="mark" href="/" aria-label="LinkSpin home" title="LinkSpin"></a>'
|
app.innerHTML = '<nav class="rail" aria-label="LinkSpin"><a class="mark" href="/" aria-label="LinkSpin home" title="LinkSpin"></a>'
|
||||||
+ NAV.map(([k, label, href, svg, sec]) => '<a ' + (k === 'help' ? 'id="crHelp" ' : '') + 'href="' + (BUILT.has(k) ? href : FALLBACK[k]) + '"' + (k === act ? ' class="on' + (sec ? ' rsec' : '') + '" aria-current="page"' : (sec ? ' class="rsec"' : '')) + ' title="' + label + '" aria-label="' + label + '"><svg viewBox="0 0 24 24">' + svg + '</svg><span class="lbl">' + label + '</span></a>').join('')
|
+ NAV.map(([k, label, href, svg, sec]) => '<a ' + (k === 'help' ? 'id="crHelp" ' : k === 'tank' ? 'id="crTank" hidden ' : '') + (/^https?:/.test(href) ? 'target="_blank" rel="noopener" ' : '') + 'href="' + (BUILT.has(k) ? href : FALLBACK[k]) + '"' + (k === act ? ' class="on' + (sec ? ' rsec' : '') + '" aria-current="page"' : (sec ? ' class="rsec"' : '')) + ' title="' + label + '" aria-label="' + label + '"><svg viewBox="0 0 24 24">' + svg + '</svg><span class="lbl">' + label + '</span></a>').join('')
|
||||||
+ '<span class="sp"></span><button class="railtog" type="button" id="crRailTog" title="Collapse or expand the menu" aria-label="Collapse or expand the menu"><svg viewBox="0 0 24 24"><path d="M15 6l-6 6 6 6"/></svg><span class="lbl">Collapse</span></button></nav>'
|
+ '<span class="sp"></span><button class="railtog" type="button" id="crRailTog" title="Collapse or expand the menu" aria-label="Collapse or expand the menu"><svg viewBox="0 0 24 24"><path d="M15 6l-6 6 6 6"/></svg><span class="lbl">Collapse</span></button></nav>'
|
||||||
+ '<div class="main"><div class="topbar"><div><div class="crumb">' + esc(o.crumb || 'Control room') + '</div><h1>' + esc(o.title || '') + '</h1></div><span class="readout" id="crSub">' + esc(o.sub || '') + '</span><span class="grow"></span><span id="crActions">' + (o.actions || '') + '</span>' + themeSeg('crTheme') + '<button class="who" type="button" id="crUserBtn" title="Account"><i id="crAv"></i><span id="crWho">Sign in</span></button></div>'
|
+ '<div class="main"><div class="topbar"><div><div class="crumb">' + esc(o.crumb || 'Control room') + '</div><h1>' + esc(o.title || '') + '</h1></div><span class="readout" id="crSub">' + esc(o.sub || '') + '</span><span class="grow"></span><span id="crActions">' + (o.actions || '') + '</span>' + themeSeg('crTheme') + '<button class="who" type="button" id="crUserBtn" title="Account"><i id="crAv"></i><span id="crWho">Sign in</span></button></div>'
|
||||||
// pre-launch notice (Marty, 2026-10-17): open to everyone from today, official launch November 15
|
// pre-launch notice (Marty, 2026-10-17): open to everyone from today, official launch November 15; date-driven since 2026-11-02 so it drops off by itself at midnight Central on launch day
|
||||||
+ '<div class="prelaunch" role="note"><b>Pre-launch testing until November 15.</b> Everything is live and working, but features and screens may change while we test. Questions? Use <a href="/help">Help</a>.</div>'
|
+ (prelaunch() ? '<div class="prelaunch" role="note"><b>Pre-launch testing until November 15.</b> Everything is live and working, but features and screens may change while we test. Questions? Use <a href="/help">Help</a>.</div>' : '')
|
||||||
+ arriveStrip() + '<div id="crBody"></div>'
|
+ arriveStrip() + '<div id="crBody"></div>'
|
||||||
+ '<div class="strip" id="crStrip"><span><span class="dot off" id="stDot"></span>rotator <b id="stHealth">checking</b></span><span>served today <b id="stServed">·</b></span><span>zones live <b id="stZones">·</b></span><span>network <b id="stNet">·</b></span><span class="grow"></span><span id="stClock"></span></div></div>';
|
+ '<div class="strip" id="crStrip"><span><span class="dot off" id="stDot"></span>rotator <b id="stHealth">checking</b></span><span>served today <b id="stServed">·</b></span><span>zones live <b id="stZones">·</b></span><span>network <b id="stNet">·</b></span><span class="grow"></span><span id="stClock"></span></div></div>';
|
||||||
page.parentNode.insertBefore(app, page); app.querySelector('#crBody').appendChild(page);
|
page.parentNode.insertBefore(app, page); app.querySelector('#crBody').appendChild(page);
|
||||||
@@ -210,16 +216,63 @@ window.CR = (function () {
|
|||||||
}
|
}
|
||||||
return m;
|
return m;
|
||||||
}
|
}
|
||||||
|
// Holding tank on the rail (Marty 2026-11-11): only for members who can adopt (their own qualifying package, payouts on),
|
||||||
|
// a badge with how many can be adopted right now, and the at-one-time cap from the site setting in its title and on the card
|
||||||
|
function badgeCss() {
|
||||||
|
if (!document.getElementById('crHelpCss')) { const st = document.createElement('style'); st.id = 'crHelpCss'; st.textContent = '.rail a .rbadge{position:absolute;top:3px;right:3px;min-width:16px;height:16px;padding:0 4px;border-radius:999px;background:var(--sig);color:#fff;font:700 10px/16px var(--mono);text-align:center;box-sizing:border-box}.rail.wide a .rbadge,.app.wide .rail a .rbadge{right:8px;top:50%;transform:translateY(-50%)}'; document.head.appendChild(st); }
|
||||||
|
}
|
||||||
|
async function tankItem() {
|
||||||
|
const a = $('crTank'); if (!a) return null;
|
||||||
|
let r = null; try { r = await get('/api/my/tank/summary'); } catch (e) { return null; }
|
||||||
|
if (!r || !r.adopter) { a.hidden = true; return r; }
|
||||||
|
a.hidden = false; const cap = Number(r.cap) || 0;
|
||||||
|
const t = 'Holding tank: ' + (r.waiting ? fmt(r.waiting) + ' waiting for a sponsor' : 'nobody waiting right now') + '. You can adopt up to ' + cap + ' people at a time.';
|
||||||
|
a.title = t; a.setAttribute('aria-label', t);
|
||||||
|
badgeCss();
|
||||||
|
let b = a.querySelector('.rbadge'); if (!r.waiting) { if (b) b.remove(); } else { if (!b) { b = document.createElement('b'); b.className = 'rbadge'; a.appendChild(b); } b.textContent = r.waiting > 999 ? '999+' : String(r.waiting); }
|
||||||
|
return r;
|
||||||
|
}
|
||||||
// Help badge on the rail: how many of the member's tickets have a reply from Marty they have not opened (helpdesk.js)
|
// Help badge on the rail: how many of the member's tickets have a reply from Marty they have not opened (helpdesk.js)
|
||||||
async function helpBadge() {
|
async function helpBadge() {
|
||||||
const a = $('crHelp'); if (!a) return 0;
|
const a = $('crHelp'); if (!a) return 0;
|
||||||
let n = 0; try { n = Number((await get('/api/my/support/unread')).unread) || 0; } catch (e) { return 0; }
|
let n = 0; try { n = Number((await get('/api/my/support/unread')).unread) || 0; } catch (e) { return 0; }
|
||||||
if (!document.getElementById('crHelpCss')) { const st = document.createElement('style'); st.id = 'crHelpCss'; st.textContent = '.rail a .rbadge{position:absolute;top:3px;right:3px;min-width:16px;height:16px;padding:0 4px;border-radius:999px;background:var(--sig);color:#fff;font:700 10px/16px var(--mono);text-align:center;box-sizing:border-box}.rail.wide a .rbadge,.app.wide .rail a .rbadge{right:8px;top:50%;transform:translateY(-50%)}'; document.head.appendChild(st); }
|
badgeCss();
|
||||||
let b = a.querySelector('.rbadge'); if (!n) { if (b) b.remove(); return 0; }
|
let b = a.querySelector('.rbadge'); if (!n) { if (b) b.remove(); return 0; }
|
||||||
if (!b) { b = document.createElement('b'); b.className = 'rbadge'; a.appendChild(b); }
|
if (!b) { b = document.createElement('b'); b.className = 'rbadge'; a.appendChild(b); }
|
||||||
b.textContent = n > 9 ? '9+' : String(n); a.title = 'Help: ' + n + ' new repl' + (n === 1 ? 'y' : 'ies'); return n;
|
b.textContent = n > 9 ? '9+' : String(n); a.title = 'Help: ' + n + ' new repl' + (n === 1 ? 'y' : 'ies'); return n;
|
||||||
}
|
}
|
||||||
async function requireSession(onReady) { let m = await me(); whoPaint(m); themeSync(m); if (m && m.signedIn) { strip(); helpBadge(); m = await ensureUsername(m); await loginAd(); return onReady(m); } signInFlow(async r => { whoPaint(r); themeSync(r); strip(); helpBadge(); await loginAd(); onReady(r); }); }
|
// "Who invited you?" (Marty approved 2026-11-07): a member with no sponsor and no member number can name who invited them.
|
||||||
|
// LinkSpin members land on the Control Room, not on the /tools Overview, so it sits at the top of every screen, /tools included.
|
||||||
|
// Soft: nothing waits for it. "Nobody invited me" hides it everywhere; a small link on /tools brings it back.
|
||||||
|
function inviteCard(m) {
|
||||||
|
if ($('crInvite')) $('crInvite').remove();
|
||||||
|
const ask = m && m.signedIn && !m.memberId && m.inviteAsk; const body = $('crBody'); if (!ask || !body) return;
|
||||||
|
if (ask.dismissed && location.pathname !== '/tools') return;
|
||||||
|
if (!$('crInviteCss')) { const st = document.createElement('style'); st.id = 'crInviteCss'; st.textContent = '.invite{margin:12px 24px;padding:12px 14px;border:1px solid var(--line);background:var(--panel)}.invite h2{font:700 16px Manrope,system-ui;margin:0 0 4px}.invite .row{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px;align-items:center}.invite .field{flex:1 1 180px;max-width:280px;margin:0}.invite .bad{color:var(--bad,#c0392b)}@media(max-width:640px){.invite{margin:10px 16px}}'; document.head.appendChild(st); }
|
||||||
|
const box = document.createElement('div'); box.id = 'crInvite'; box.className = 'invite'; body.insertBefore(box, body.firstChild);
|
||||||
|
const full = () => {
|
||||||
|
box.innerHTML = '<h2>Who invited you?</h2><div class="ink2">You joined without a sponsor. If someone told you about LinkSpin, type their username and they become your sponsor. Do it before your payouts switch on or you buy: your sponsor locks on the contract at that point.</div>'
|
||||||
|
+ '<div class="row"><input class="field" id="inviteWho" autocomplete="off" autocapitalize="none" spellcheck="false" aria-label="Their username" placeholder="their username"><button class="btn pri" type="button" id="inviteGo">Set my sponsor</button><button class="btn" type="button" id="inviteNo">Nobody invited me</button></div><div class="ink2" id="inviteMsg" style="margin-top:6px"></div>';
|
||||||
|
const say = (t, bad) => { const x = $('inviteMsg'); x.textContent = t || ''; x.classList.toggle('bad', !!bad); };
|
||||||
|
const go = async () => {
|
||||||
|
say('');
|
||||||
|
try {
|
||||||
|
const who = $('inviteWho').value;
|
||||||
|
const chk = await api('/api/my/tank/invited', { who, check: true });
|
||||||
|
const yes = await dialog({ title: 'Who invited you?', text: chk.name + ' becomes your sponsor. ' + (m.address ? 'Your wallet is linked, so your payouts switch on under them right away, and that locks them in for good on the contract.' : 'Your sponsor locks on the contract when your payouts switch on or you buy, so check this is the right person.'), ok: 'Yes, ' + chk.name, no: 'Not them' });
|
||||||
|
if (!yes) return;
|
||||||
|
const r = await api('/api/my/tank/invited', { who });
|
||||||
|
box.remove(); toast(r.name + ' is now your sponsor.'); setTimeout(() => location.reload(), 1400);
|
||||||
|
} catch (e) { say(e.message, true); }
|
||||||
|
};
|
||||||
|
$('inviteGo').addEventListener('click', go);
|
||||||
|
$('inviteWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); go(); } });
|
||||||
|
$('inviteNo').addEventListener('click', async () => { try { await api('/api/my/tank/invited/dismiss', {}); } catch (e) {} if (location.pathname === '/tools') small(); else box.remove(); });
|
||||||
|
};
|
||||||
|
const small = () => { box.innerHTML = '<span class="ink2">Remembered who invited you? <a href="#" id="inviteBack">Tell us</a></span>'; $('inviteBack').addEventListener('click', e => { e.preventDefault(); full(); $('inviteWho').focus(); }); };
|
||||||
|
if (ask.dismissed) small(); else full();
|
||||||
|
}
|
||||||
|
async function requireSession(onReady) { let m = await me(); whoPaint(m); themeSync(m); if (m && m.signedIn) { strip(); helpBadge(); tankItem(); m = await ensureUsername(m); await loginAd(); inviteCard(m); return onReady(m); } signInFlow(async r => { whoPaint(r); themeSync(r); strip(); helpBadge(); await loginAd(); me(true).then(inviteCard); onReady(r); }); }
|
||||||
// tiles with a sparkline and a delta chip (Instrument scheme, 2026-09-29): series = numbers oldest first
|
// tiles with a sparkline and a delta chip (Instrument scheme, 2026-09-29): series = numbers oldest first
|
||||||
function sparkline(series) {
|
function sparkline(series) {
|
||||||
const s = (series || []).map(Number); if (s.length < 2 || !s.some(Boolean)) return '';
|
const s = (series || []).map(Number); if (s.length < 2 || !s.some(Boolean)) return '';
|
||||||
@@ -238,5 +291,20 @@ window.CR = (function () {
|
|||||||
return '<div class="tile' + (o.hi ? ' hi' : '') + '"><span class="k">' + esc(o.k) + '</span><div class="row"><span class="v">' + o.v + (o.unit ? '<small>' + esc(o.unit) + '</small>' : '') + '</span>' + sparkline(o.series) + '</div>'
|
return '<div class="tile' + (o.hi ? ' hi' : '') + '"><span class="k">' + esc(o.k) + '</span><div class="row"><span class="v">' + o.v + (o.unit ? '<small>' + esc(o.unit) + '</small>' : '') + '</span>' + sparkline(o.series) + '</div>'
|
||||||
+ (o.delta ? '<span class="delta' + (o.delta.cls ? ' ' + o.delta.cls : '') + '">' + esc(o.delta.text) + '</span>' : '') + (o.note ? '<span class="muted mono" style="font-size:11px">' + esc(o.note) + '</span>' : '') + '</div>';
|
+ (o.delta ? '<span class="delta' + (o.delta.cls ? ' ' + o.delta.cls : '') + '">' + esc(o.delta.text) + '</span>' : '') + (o.note ? '<span class="muted mono" style="font-size:11px">' + esc(o.note) + '</span>' : '') + '</div>';
|
||||||
}
|
}
|
||||||
return { esc, fmt, api, get, copy, dialog, toast, mount, sub, me, requireSession, signInFlow, tile, sparkline, delta, helpBadge };
|
return { esc, fmt, api, get, copy, dialog, toast, mount, sub, me, requireSession, signInFlow, tile, sparkline, delta, helpBadge, tankItem };
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Network links (2026-11-13): a click on a link to InstantAdPay goes through /go/iap, which signs a signed-in member in over there and is a
|
||||||
|
// plain redirect for everyone else. Rewritten at click time only, so links people copy to share stay clean. data-nogo opts a link out.
|
||||||
|
(function () {
|
||||||
|
if (window.__netlinks) return; window.__netlinks = 1;
|
||||||
|
const HOSTS = ['instantadpay.com', 'www.instantadpay.com'];
|
||||||
|
document.addEventListener('click', e => {
|
||||||
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||||
|
const a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
|
||||||
|
if (!a || a.hasAttribute('download') || a.hasAttribute('data-nogo')) return;
|
||||||
|
let u; try { u = new URL(a.href); } catch (x) { return; }
|
||||||
|
if (u.protocol !== 'https:' || !HOSTS.includes(u.hostname)) return;
|
||||||
|
a.href = '/go/iap?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
||||||
|
}, true);
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -152,7 +152,7 @@
|
|||||||
function tankHoldText(h) {
|
function tankHoldText(h) {
|
||||||
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
|
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
|
||||||
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
|
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
|
||||||
return t;
|
return t + ' Did someone invite you? Tell us in the Who invited you box.';
|
||||||
}
|
}
|
||||||
// a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default)
|
// a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default)
|
||||||
function holdText(sp) {
|
function holdText(sp) {
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
||||||
let FROM = 'iap';
|
let FROM = 'iap';
|
||||||
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
||||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return u.href; } catch (e) { return url; } };
|
// a link to the other site goes through this site's /go/<other> hop (network sign-in, 2026-11-12): the member arrives signed in
|
||||||
|
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return '/go/' + (FROM === 'iap' ? 'linkspin' : 'iap') + '?to=' + encodeURIComponent(u.pathname + u.search + u.hash); } catch (e) { return url; } };
|
||||||
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
||||||
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
||||||
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
: '<p style="margin:0 0 8px">Next refuel day <b>' + esc(v.refuelDayLabel) + '</b> (Central). Window opens ' + esc(v.opensLabel) + ', grace to ' + esc(v.graceLabel) + '.</p>';
|
: '<p style="margin:0 0 8px">Next refuel day <b>' + esc(v.refuelDayLabel) + '</b> (Central). Window opens ' + esc(v.opensLabel) + ', grace to ' + esc(v.graceLabel) + '.</p>';
|
||||||
if (c.month) h += '<div style="margin:0 0 8px">' + site('InstantAdPay', c.iap, v.minUsd.iap) + site('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</div>';
|
if (c.month) h += '<div style="margin:0 0 8px">' + site('InstantAdPay', c.iap, v.minUsd.iap) + site('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</div>';
|
||||||
if (!v.windowOpen && c.month && !c.both) h += '<p class="muted" style="margin:0 0 8px">Refuel ' + (c.linkspin && c.linkspin.refueled ? 'InstantAdPay ($' + v.minUsd.iap + '+)' : 'LinkSpin ($' + v.minUsd.linkspin + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to +' + v.next.secondEngine + '%.'
|
if (!v.windowOpen && c.month && !c.both) h += '<p class="muted" style="margin:0 0 8px">Refuel ' + (c.linkspin && c.linkspin.refueled ? 'InstantAdPay ($' + v.minUsd.iap + '+)' : 'LinkSpin ($' + v.minUsd.linkspin + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to +' + v.next.secondEngine + '%.'
|
||||||
+ (c.linkspin && c.linkspin.refueled ? ' <a href="https://instantadpay.com/my#buy" target="_blank" rel="noopener">Buy on InstantAdPay ↗</a>' : '') + '</p>';
|
+ (c.linkspin && c.linkspin.refueled ? ' <a href="/go/iap?to=%2Fmy%23buy" target="_blank" rel="noopener">Buy on InstantAdPay ↗</a>' : '') + '</p>';
|
||||||
if (v.pitStop && (v.pitStop.linkspin || v.pitStop.usedLinkspin)) h += '<p class="muted" style="margin:0 0 8px"><b>Pit Stop</b> ' + (v.pitStop.linkspin ? 'available here: +' + v.pitStop.pct + '% on a $' + v.minUsd.linkspin + '+ top-up, once this cycle. It does not count as your refuel.' : 'used here this cycle.') + '</p>';
|
if (v.pitStop && (v.pitStop.linkspin || v.pitStop.usedLinkspin)) h += '<p class="muted" style="margin:0 0 8px"><b>Pit Stop</b> ' + (v.pitStop.linkspin ? 'available here: +' + v.pitStop.pct + '% on a $' + v.minUsd.linkspin + '+ top-up, once this cycle. It does not count as your refuel.' : 'used here this cycle.') + '</p>';
|
||||||
h += '<p class="muted" style="margin:0 0 10px">' + (v.freeMiss.available ? 'One free miss left this year.' : 'Free miss for this year used.') + '</p>';
|
h += '<p class="muted" style="margin:0 0 10px">' + (v.freeMiss.available ? 'One free miss left this year.' : 'Free miss for this year used.') + '</p>';
|
||||||
const lsDone = c.linkspin && c.linkspin.refueled;
|
const lsDone = c.linkspin && c.linkspin.refueled;
|
||||||
|
|||||||
@@ -89,3 +89,14 @@
|
|||||||
finally { $('verifyBtn').disabled = false; }
|
finally { $('verifyBtn').disabled = false; }
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// Signed in already (an email code here, or network sign-in from InstantAdPay): the header buttons open the dashboard instead of
|
||||||
|
// offering Sign in / Start free again (Marty 2026-11-13: arrived signed in from InstantAdPay and the home page still said Sign in)
|
||||||
|
(function () {
|
||||||
|
fetch('/api/me', { credentials: 'same-origin', cache: 'no-store' }).then(r => r.json()).then(me => {
|
||||||
|
if (!me || !me.signedIn) return;
|
||||||
|
const btns = document.querySelectorAll('header [data-join]');
|
||||||
|
if (btns.length) { btns[0].textContent = 'Open my dashboard'; btns[0].href = '/ads'; btns[0].removeAttribute('data-join'); btns[0].className = 'btn pri'; }
|
||||||
|
for (let i = 1; i < btns.length; i++) btns[i].hidden = true;
|
||||||
|
}).catch(() => {});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -13,10 +13,11 @@
|
|||||||
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and the contract holds zero balance.', points: ['Every payout is public. Click it, read it, verify it.', 'The contract has no pause button and no owner power over money.', 'Join free by email. The ledger is one click from your dashboard.'], cta: 'Check the ledger yourself, then decide', sub: 'free account by email' },
|
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and the contract holds zero balance.', points: ['Every payout is public. Click it, read it, verify it.', 'The contract has no pause button and no owner power over money.', 'Join free by email. The ledger is one click from your dashboard.'], cta: 'Check the ledger yourself, then decide', sub: 'free account by email' },
|
||||||
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you half of their package from their very first purchase. Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', points: ['Half of every direct purchase, instantly.', 'Level 2 at two qualifying buyers, level 3 at five.', 'Your invite link is live the moment you are in.'], cta: 'Start your line. Two buyers is the target.', sub: 'free account by email' },
|
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you half of their package from their very first purchase. Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', points: ['Half of every direct purchase, instantly.', 'Level 2 at two qualifying buyers, level 3 at five.', 'Your invite link is live the moment you are in.'], cta: 'Start your line. Two buyers is the target.', sub: 'free account by email' },
|
||||||
links: { video: 'links', eyebrow: 'One link, every page you promote', h: 'Stop <em>juggling links.</em>', lead: 'One short link stands in for all of yours. Behind it, the pages you promote, served in turn by the weights you set, with hours, caps and a fallback. The link never changes, so every copy out in the world keeps working.', points: ['Weights, hours of the day, daily caps, a fallback.', 'A report by source, country and device; your tracker click id filled in.', 'Free. Try a spin on the home page with no account.'], cta: 'Make your first spin link', sub: 'free account by email' },
|
links: { video: 'links', eyebrow: 'One link, every page you promote', h: 'Stop <em>juggling links.</em>', lead: 'One short link stands in for all of yours. Behind it, the pages you promote, served in turn by the weights you set, with hours, caps and a fallback. The link never changes, so every copy out in the world keeps working.', points: ['Weights, hours of the day, daily caps, a fallback.', 'A report by source, country and device; your tracker click id filled in.', 'Free. Try a spin on the home page with no account.'], cta: 'Make your first spin link', sub: 'free account by email' },
|
||||||
pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. <em>Get a page.</em>', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list: CSV or webhook.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' },
|
pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. <em>Get a page.</em>', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list with a CSV download, or paste your autoresponder form.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' },
|
||||||
zones: { video: 'zones', eyebrow: 'Your site pays you', h: 'One script tag. <em>Ad credits for every viewable view.</em>', lead: 'A zone is an ad slot on your own site in any of nine sizes. Member campaigns show first, then network ads, then a house banner. Viewable impressions pay you ad credits you spend on your own campaigns.', points: ['Viewable = half the banner on screen for one second. Bots never count.', 'Paid ads only on the site you declared.', 'Credits spend on your own banner or text campaign.'], cta: 'Add a zone, paste the tag', sub: 'free account by email' },
|
zones: { video: 'zones', eyebrow: 'Your site pays you', h: 'One script tag. <em>Ad credits for every viewable view.</em>', lead: 'A zone is an ad slot on your own site in any of nine sizes. Member campaigns show first, then network ads, then a house banner. Viewable impressions pay you ad credits you spend on your own campaigns.', points: ['Viewable = half the banner on screen for one second. Bots never count.', 'Paid ads only on the site you declared.', 'Credits spend on your own banner or text campaign.'], cta: 'Add a zone, paste the tag', sub: 'free account by email' },
|
||||||
audiences: { video: 'audiences', eyebrow: 'Retargeting, built in', h: 'Reach your own visitors <em>again.</em>', lead: 'Everyone who views your pages or your zones is remembered for 30 days in an audience you own. Paste a pixel on any other site you control. Then show a campaign only to them, or never to them.', points: ['My visitors is automatic. Named audiences take one pixel line.', 'Show only to, or never show to, on any banner or text campaign.', 'Honest match: cookie plus a 24-hour fallback, nothing personal stored.'], cta: 'See your audiences', sub: 'free account by email' },
|
audiences: { video: 'audiences', eyebrow: 'Retargeting, built in', h: 'Reach your own visitors <em>again.</em>', lead: 'Everyone who views your pages or your zones is remembered for 30 days in an audience you own. Paste a pixel on any other site you control. Then show a campaign only to them, or never to them.', points: ['My visitors is automatic. Named audiences take one pixel line.', 'Show only to, or never show to, on any banner or text campaign.', 'Honest match: cookie plus a 24-hour fallback, nothing personal stored.'], cta: 'See your audiences', sub: 'free account by email' },
|
||||||
stack: { video: 'stack', eyebrow: 'Three tools, zero dollars', h: 'A rotator, a page builder, an ad slot. <em>Free.</em>', lead: 'Join with just an email and the whole stack is yours: spin links, bridge pages and a zone for your site. View a few ads a day and you earn credits for your first campaign. Buy a package only if you want more.', points: ['No wallet, no card, nothing to install.', 'Spin links, pages and zones never need a package.', 'Packages from $10 when you want more reach.'], cta: 'Start with the free stack', sub: 'type your email, get a code, that is the whole signup' },
|
stack: { video: 'stack', eyebrow: 'Three tools, zero dollars', h: 'A rotator, a page builder, an ad slot. <em>Free.</em>', lead: 'Join with just an email and the whole stack is yours: spin links, bridge pages and a zone for your site. View a few ads a day and you earn credits for your first campaign. Buy a package only if you want more.', points: ['No wallet, no card, nothing to install.', 'Spin links, pages and zones never need a package.', 'Packages from $10 when you want more reach.'], cta: 'Start with the free stack', sub: 'type your email, get a code, that is the whole signup' },
|
||||||
|
b4h: { eyebrow: 'BTC4Hits is now LinkSpin', h: 'BTC4Hits is now <em>LinkSpin.</em>', lead: 'Your BTC4Hits account came with you. Sign in with the email you used there; an active rotator is already waiting as a LinkSpin spin link.', points: ['Sign in with your BTC4Hits email. We send a code, no password.', 'Active rotator links keep working and now forward through LinkSpin.', 'New here? The same box makes you a free account.'], cta: 'Sign in with your email', sub: 'same email as BTC4Hits, we send you a code', ctaBtn: 'Sign in with your BTC4Hits email' },
|
||||||
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10.', points: ['Views are timed on the server, so a real person saw your ad.', 'Your ads run in the viewer, on member sites and across the partner network.', 'Rotate the pages you promote with one spin link, free.'], cta: 'Put your next ad dollar where it pays you back', sub: 'free account by email, see every rate before you buy' }
|
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10.', points: ['Views are timed on the server, so a real person saw your ad.', 'Your ads run in the viewer, on member sites and across the partner network.', 'Rotate the pages you promote with one spin link, free.'], cta: 'Put your next ad dollar where it pays you back', sub: 'free account by email, see every rate before you buy' }
|
||||||
};
|
};
|
||||||
const v = (new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '').toLowerCase();
|
const v = (new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '').toLowerCase();
|
||||||
@@ -28,7 +29,7 @@
|
|||||||
$('jnPoints').innerHTML = a.points.map(t => '<li>' + esc(t) + '</li>').join(''); $('jnPoints').hidden = false;
|
$('jnPoints').innerHTML = a.points.map(t => '<li>' + esc(t) + '</li>').join(''); $('jnPoints').hidden = false;
|
||||||
// the hook video (16:9 cut on Spaces) + a call to action that jumps to the email box
|
// the hook video (16:9 cut on Spaces) + a call to action that jumps to the email box
|
||||||
if (a.video) { const VID = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/linkspin/promo/'; const v = $('jnVideo'); v.src = VID + a.video + '.mp4'; v.poster = VID + a.video + '.jpg'; $('jnVideoWrap').hidden = false; }
|
if (a.video) { const VID = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/linkspin/promo/'; const v = $('jnVideo'); v.src = VID + a.video + '.mp4'; v.poster = VID + a.video + '.jpg'; $('jnVideoWrap').hidden = false; }
|
||||||
$('jnCtaRow').hidden = false;
|
$('jnCtaRow').hidden = false; if (a.ctaBtn) $('jnCta').textContent = a.ctaBtn;
|
||||||
$('jnCta').addEventListener('click', e => { e.preventDefault(); const em = $('jnEmail'); em.scrollIntoView({ behavior: 'smooth', block: 'center' }); setTimeout(() => em.focus(), 450); });
|
$('jnCta').addEventListener('click', e => { e.preventDefault(); const em = $('jnEmail'); em.scrollIntoView({ behavior: 'smooth', block: 'center' }); setTimeout(() => em.focus(), 450); });
|
||||||
}
|
}
|
||||||
// ?name=First personalises the page (site-owner links): letters, spaces, hyphens, apostrophes only, 30 chars
|
// ?name=First personalises the page (site-owner links): letters, spaces, hyphens, apostrophes only, 30 chars
|
||||||
|
|||||||
+34
-50
@@ -15,87 +15,71 @@
|
|||||||
const pb = $('printBtn'); if (pb) pb.addEventListener('click', () => window.print());
|
const pb = $('printBtn'); if (pb) pb.addEventListener('click', () => window.print());
|
||||||
const tok = me.username || me.refCode || me.memberId;
|
const tok = me.username || me.refCode || me.memberId;
|
||||||
if (tok) document.querySelectorAll('[data-link]').forEach(el => { el.textContent = location.origin + '/join/' + tok; });
|
if (tok) document.querySelectorAll('[data-link]').forEach(el => { el.textContent = location.origin + '/join/' + tok; });
|
||||||
// launch week swipes: four promoter emails, the member's link + FOUNDER code filled in (Marty, 2026-09-15)
|
// launch swipes for LinkSpin's public launch, Sun 2026-11-15 6 AM Central (copy from campaign-2026-11/SWIPES.md, facts
|
||||||
const LINK = location.origin + '/join/' + (tok || '') + '?promo=FOUNDER';
|
// checked 2026-11-02). Replaced InstantAdPay's September founding-week set and its FOUNDER code (Marty 2026-11-05).
|
||||||
|
const BASE = location.origin + '/join/' + (tok || '');
|
||||||
|
const fill = t => t.replace(/\{link(?::(\w+))?\}/g, (m, v) => v ? BASE + '?v=' + v : BASE);
|
||||||
const SW = [
|
const SW = [
|
||||||
{ when: 'Day 1 · six days out', subject: 'Something opens Monday. I am bringing a few people in early.', body: `Quick one, because I want you positioned before this goes public.
|
{ when: 'Short · any day before Sunday', subject: 'Opens to the world Sunday, 6 AM Central', body: `Quick one.
|
||||||
|
|
||||||
I have been inside a new advertising platform for a week. It pays sponsors in the same transaction a package is bought, wallet to wallet, on the Polygon ledger where anyone can check it. No back office. No payday. I have watched the payouts land.
|
LinkSpin opens to the world on Sunday, November 15 at 6 AM Central. I have been using it through pre-launch: one short link that rotates every page I promote, a bridge page built from any offer in a minute, and an ad slot on my site that pays me ad credits. All three are free with an email.
|
||||||
|
|
||||||
It opens to everyone Monday, September 21 at 9 AM Central. Founding members are in now, and the people they bring in before then are the ones the launch traffic lands under.
|
The paid side is advertising. A package buys ad credits, one cent each, and a public contract on Polygon splits each package to the sponsor line in the same transaction. Every payout is on the ledger.
|
||||||
|
|
||||||
Joining is free with an email. This week the code FOUNDER gives you 500 ad credits to run a campaign on day one:
|
Join before Sunday and you are placed under me; join after and you still get the same tools: {link}
|
||||||
|
|
||||||
{link}
|
Ad credits buy advertising, not income. Crypto carries risk of loss.`},
|
||||||
|
{ when: 'Standard · the rotator story', subject: 'The rotator I wish I had ten years ago', body: `I have run link rotators for years and never trusted one. The clicks never matched my tracker, dead links kept serving, and there was no report worth reading.
|
||||||
|
|
||||||
No income is promised. It is an ad platform with a referral program. But the payment mechanics are real and public, and that is why I am in.
|
LinkSpin is the first one I keep open all day.
|
||||||
|
|
||||||
Look before Monday. I will walk you through the first three steps.`},
|
One short link stands in for every page I promote. I set the share each page gets, give a page hours of the day, pause it when it stops pulling, and name a fallback. Every destination is health-checked every 30 minutes and paused for me if it dies. My tracker's click id rides through. The report shows which page converts, by source, country and device, with bots dropped on the server.
|
||||||
{ when: 'Day 2 · five days out', subject: 'Five hundred free credits, and what you can do with them', body: `Yesterday I sent you a link. Here is what is on the other side of it.
|
|
||||||
|
|
||||||
You join free with your email. Every day you view a short set of ads and earn credits. Credits run your own ads: banners, text ads, video ads, solo mailings, verified visits, across the whole network.
|
It also builds a bridge, review or squeeze page from any offer I paste in, published on a clean domain with the leads going to my list. And one script tag turns the empty ad space on my site into a zone that pays me ad credits.
|
||||||
|
|
||||||
This week the FOUNDER code adds 500 credits on top the moment you join, enough to launch a real campaign pointed at whatever you are promoting. Watch it deliver before Monday, when everyone else arrives.
|
All of that is free with an email. The paid side is advertising: six packages, $10 to $500, one credit per cent of delivery, and a verified contract on Polygon that splits each package to the sponsor line in the same transaction it sells in.
|
||||||
|
|
||||||
The other half is simple. When someone you invite buys an ad package, the contract pays you 50 percent instantly. Level two gets 20 percent, level three 10 percent. Same transaction, on the public ledger.
|
LinkSpin opens to the world Sunday, November 15 at 6 AM Central. Have a look before then: {link:links}
|
||||||
|
|
||||||
{link}
|
Ad credits buy advertising, not income. Payouts come only from purchases in your line. Crypto carries risk of loss.`}
|
||||||
|
|
||||||
Use the code before it expires Monday morning. Then tell me you are in and I will show you the checklist.`},
|
|
||||||
{ when: 'Day 4 · the weekend', subject: 'The two people you bring in this weekend', body: `The doors open Monday morning and I am spending the weekend getting my first people set up. I want you to be one of them.
|
|
||||||
|
|
||||||
Here is why the weekend matters. Everyone who joins now is a founding member. The traffic that arrives Monday lands under whoever is already in and set up. Two people under you before Monday, and your line is built when the wave hits.
|
|
||||||
|
|
||||||
Setup takes ten minutes: username, link a wallet, switch on payouts. Then share your link. The site gives you posts, swipes, banners and a leaderboard with weekly credit prizes for the top sponsors.
|
|
||||||
|
|
||||||
Join with the FOUNDER code and the 500 credits are yours:
|
|
||||||
|
|
||||||
{link}
|
|
||||||
|
|
||||||
Message me when you are in and I will go through the checklist with you before Monday.`},
|
|
||||||
{ when: 'Day 6 · Sunday evening', subject: 'Doors open tomorrow at 9 AM Central', body: `Last note before the launch.
|
|
||||||
|
|
||||||
LinkSpin opens to the public tomorrow, Monday, at 9 AM Central. After that the FOUNDER code is gone. Tonight it still gives you 500 free ad credits.
|
|
||||||
|
|
||||||
If you join tonight you are in as a founding member with a campaign already funded and your link ready when the first wave arrives. If you wait, you join the wave.
|
|
||||||
|
|
||||||
Free to join, real advertising, and every payment lands in your own wallet the second it happens, on a ledger anyone can read. No income promises. Just mechanics you can verify.
|
|
||||||
|
|
||||||
{link}
|
|
||||||
|
|
||||||
I will be online from 8 AM tomorrow walking people through the first three steps. Get in tonight and you are ahead of them.`}
|
|
||||||
];
|
];
|
||||||
// short posts and a DM for the same days, one per day, link + code included
|
|
||||||
const POSTS = [
|
const POSTS = [
|
||||||
{ when: 'Day 1 · six days out', text: `Something I have been inside for a week opens to the public Monday, September 21 at 9 AM Central. An ad platform that pays sponsors in the same transaction a package is bought, on the Polygon ledger where anyone can check it. Free to join. Code FOUNDER gives you 500 ad credits before then. No income promises, just mechanics you can verify. {link}` },
|
{ when: 'X · one link', text: `One short link that rotates every page I promote, with weights, hours and a fallback, and a report that shows which page converts. LinkSpin is open for pre-launch and goes live to the world Nov 15. Free, try a spin with no account: {link:links}` },
|
||||||
{ when: 'Day 2 · five days out', text: `500 free ad credits for joining before Monday. View a short daily set of ads, earn more, run banners, text ads, video ads and solo mailings across the network. When someone you invite buys a package, the contract pays you 50 percent instantly, wallet to wallet. Code FOUNDER. {link}` },
|
{ when: 'Facebook · three tools', text: `Three tools I used to pay for separately, now free with an email address.
|
||||||
{ when: 'Day 4 · the weekend', text: `The doors open Monday morning. Everyone joining this weekend is a founding member, and the launch traffic lands under whoever is already set up. Ten minutes to set up, 500 credits with code FOUNDER, and a leaderboard that pays weekly credit prizes to the top sponsors. {link}` },
|
|
||||||
{ when: 'Day 6 · Sunday evening', text: `Doors open tomorrow, 9 AM Central. Tonight the FOUNDER code still gives you 500 free ad credits; tomorrow it is gone. Free to join, real advertising, every payment on a public ledger. Get in tonight and you are ahead of the wave. {link}` },
|
One link that rotates every page I promote and reports which one converts. A page builder that turns any offer I paste in into a bridge, review or squeeze page on a clean domain, with the leads going to my own list. And an ad slot for my own site that pays me ad credits for every viewable view.
|
||||||
{ when: 'Text or DM · any day', text: `Hey, I am in something that opens publicly Monday and I am bringing a few people in early. Free to join, real advertising, every payment lands in your own wallet the second it happens. Use code FOUNDER for 500 free credits. Ten minutes to set up and I will walk you through it: {link}` }
|
|
||||||
|
It is open for pre-launch now and goes live to the world on Sunday, November 15. The paid side is advertising, split by a public contract on Polygon in the same transaction; read that part on the site before you spend a dollar.
|
||||||
|
|
||||||
|
{link:stack}
|
||||||
|
|
||||||
|
Ad credits buy advertising, not income. Crypto carries risk of loss.` },
|
||||||
|
{ when: 'Telegram or WhatsApp group', text: `Quick one for the group. LinkSpin opens to the world Sunday, Nov 15, 6 AM Central. Free with an email: one link that rotates every page you promote, a bridge-page builder, and an ad slot for your site that pays ad credits. Members who join before Sunday are placed under whoever brought them. Tour: {link}` },
|
||||||
|
{ when: 'Text a friend', text: `Found a link rotator that is actually free and actually reports. One link spins every page you promote. It opens to everyone Sunday 6 AM Central; join before and you are on my team: {link:links}` }
|
||||||
];
|
];
|
||||||
const pl = $('postList');
|
const pl = $('postList');
|
||||||
if (pl) {
|
if (pl) {
|
||||||
pl.innerHTML = POSTS.map((s, i) => '<div class="swipe"><div class="cap"><span>' + s.when + '</span><button type="button" class="btn sec" data-post="' + i + '">Copy post</button></div><pre>' + s.text.replace('{link}', LINK).replace(/&/g, '&').replace(/</g, '<') + '</pre></div>').join('');
|
pl.innerHTML = POSTS.map((s, i) => '<div class="swipe"><div class="cap"><span>' + s.when + '</span><button type="button" class="btn sec" data-post="' + i + '">Copy post</button></div><pre>' + fill(s.text).replace(/&/g, '&').replace(/</g, '<') + '</pre></div>').join('');
|
||||||
pl.querySelectorAll('[data-post]').forEach(b => b.addEventListener('click', async () => {
|
pl.querySelectorAll('[data-post]').forEach(b => b.addEventListener('click', async () => {
|
||||||
const t = POSTS[Number(b.dataset.post)].text.replace('{link}', LINK);
|
const t = fill(POSTS[Number(b.dataset.post)].text);
|
||||||
try { await navigator.clipboard.writeText(t); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy post'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
|
try { await navigator.clipboard.writeText(t); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy post'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
const wrap = $('swipeList');
|
const wrap = $('swipeList');
|
||||||
if (wrap) {
|
if (wrap) {
|
||||||
wrap.innerHTML = SW.map((s, i) => '<div class="swipe"><div class="cap"><span>Email ' + (i + 1) + ' · ' + s.when + '</span><button type="button" class="btn sec" data-swipe="' + i + '">Copy email</button></div><div class="subj">Subject: ' + s.subject + '</div><pre>' + s.body.replace('{link}', LINK).replace(/&/g, '&').replace(/</g, '<') + '</pre></div>').join('');
|
wrap.innerHTML = SW.map((s, i) => '<div class="swipe"><div class="cap"><span>Email ' + (i + 1) + ' · ' + s.when + '</span><button type="button" class="btn sec" data-swipe="' + i + '">Copy email</button></div><div class="subj">Subject: ' + s.subject + '</div><pre>' + fill(s.body).replace(/&/g, '&').replace(/</g, '<') + '</pre></div>').join('');
|
||||||
wrap.querySelectorAll('[data-swipe]').forEach(b => b.addEventListener('click', async () => {
|
wrap.querySelectorAll('[data-swipe]').forEach(b => b.addEventListener('click', async () => {
|
||||||
const s = SW[Number(b.dataset.swipe)]; const text = 'Subject: ' + s.subject + '\n\n' + s.body.replace('{link}', LINK);
|
const s = SW[Number(b.dataset.swipe)]; const text = 'Subject: ' + s.subject + '\n\n' + fill(s.body);
|
||||||
try { await navigator.clipboard.writeText(text); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy email'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
|
try { await navigator.clipboard.writeText(text); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy email'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); }
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// launch moment (admin: Settings > launchAt, ISO 8601 with offset)
|
// launch moment (admin: Settings > launchAt, ISO 8601 with offset)
|
||||||
const at = cfg.launchAt ? new Date(cfg.launchAt) : null;
|
const at = new Date(cfg.launchAt || '2026-11-15T06:00:00-06:00'); // public launch, Sunday 6 AM Central
|
||||||
if (at && !isNaN(at)) {
|
if (at && !isNaN(at)) {
|
||||||
$('lwWhen').hidden = false;
|
$('lwWhen').hidden = false;
|
||||||
$('lwWhenAt').textContent = at.toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
$('lwWhenAt').textContent = at.toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
||||||
const tick = () => { const ms = at - Date.now(); if (ms <= 0) { $('lwWhenIn').textContent = 'doors are open'; return; }
|
const tick = () => { const ms = at - Date.now(); if (ms <= 0) { $('lwWhenIn').textContent = 'LinkSpin is live'; return; }
|
||||||
const d = Math.floor(ms / 86400000), h = Math.floor(ms % 86400000 / 3600000), m = Math.floor(ms % 3600000 / 60000);
|
const d = Math.floor(ms / 86400000), h = Math.floor(ms % 86400000 / 3600000), m = Math.floor(ms % 3600000 / 60000);
|
||||||
$('lwWhenIn').textContent = (d ? d + 'd ' : '') + h + 'h ' + m + 'm to go'; };
|
$('lwWhenIn').textContent = (d ? d + 'd ' : '') + h + 'h ' + m + 'm to go'; };
|
||||||
tick(); setInterval(tick, 30000);
|
tick(); setInterval(tick, 30000);
|
||||||
|
|||||||
@@ -68,6 +68,7 @@
|
|||||||
return 'Checked ' + ago(h.checkedAt) + ', ' + (h.note || h.state) + (d.active ? ', strike ' + h.fails + ' of 3' + (h.fails >= 3 ? ', kept live' : ', pauses at 3') : '');
|
return 'Checked ' + ago(h.checkedAt) + ', ' + (h.note || h.state) + (d.active ? ', strike ' + h.fails + ' of 3' + (h.fails >= 3 ? ', kept live' : ', pauses at 3') : '');
|
||||||
}
|
}
|
||||||
let HE = null; // the destination editor that is open: { rid, did }
|
let HE = null; // the destination editor that is open: { rid, did }
|
||||||
|
const MANY = 60, FIRST = 50; const SHOWALL = new Set(); // big links (imported BTC4Hits rotators, hundreds of pages): first 50 rows until Show all
|
||||||
|
|
||||||
async function load(keep) {
|
async function load(keep) {
|
||||||
let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; }
|
let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; }
|
||||||
@@ -116,7 +117,8 @@
|
|||||||
const prevHost = $('destRows').querySelector('[data-he]'); const prev = prevHost && HE && Number(prevHost.dataset.he) === HE.did && prevHost.heState ? prevHost.heState() : null;
|
const prevHost = $('destRows').querySelector('[data-he]'); const prev = prevHost && HE && Number(prevHost.dataset.he) === HE.did && prevHost.heState ? prevHost.heState() : null;
|
||||||
$('autoNote').hidden = !auto.length;
|
$('autoNote').hidden = !auto.length;
|
||||||
if (auto.length) $('autoNote').textContent = 'LinkSpin paused ' + (auto.length === 1 ? 'one destination' : auto.length + ' destinations') + ' automatically after three failed checks: ' + auto.map(d => (d.label || d.url.replace(/^https?:\/\//, '')).slice(0, 40)).join(', ') + '. It comes back on its own after two clean checks, or fix the address and press Resume.';
|
if (auto.length) $('autoNote').textContent = 'LinkSpin paused ' + (auto.length === 1 ? 'one destination' : auto.length + ' destinations') + ' automatically after three failed checks: ' + auto.map(d => (d.label || d.url.replace(/^https?:\/\//, '')).slice(0, 40)).join(', ') + '. It comes back on its own after two clean checks, or fix the address and press Resume.';
|
||||||
$('destRows').innerHTML = r.destinations.length ? r.destinations.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0; const h = d.health;
|
const big = r.destinations.length > MANY && !SHOWALL.has(r.id); const rows = big ? r.destinations.slice(0, FIRST) : r.destinations;
|
||||||
|
$('destRows').innerHTML = r.destinations.length ? rows.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0; const h = d.health;
|
||||||
return '<div class="rw" data-did="' + d.id + '"><div><div class="dl"><span class="hdot ' + healthCls(h) + '" title="' + esc(healthLine(d)) + '"></span><span style="font-weight:700">' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '</span>' + (d.hours ? '<button class="hchip set" type="button" data-hc="' + d.id + '" title="This destination has its own hours">' + esc(hoursText(d.hours)) + '</button>' : '') + (h && h.frameBlocked ? '<span class="tag warn" title="This page refuses to load inside a frame (X-Frame-Options or CSP). Traffic exchanges that frame your link will show it blank.">no frames</span>' : '') + '</div>'
|
return '<div class="rw" data-did="' + d.id + '"><div><div class="dl"><span class="hdot ' + healthCls(h) + '" title="' + esc(healthLine(d)) + '"></span><span style="font-weight:700">' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '</span>' + (d.hours ? '<button class="hchip set" type="button" data-hc="' + d.id + '" title="This destination has its own hours">' + esc(hoursText(d.hours)) + '</button>' : '') + (h && h.frameBlocked ? '<span class="tag warn" title="This page refuses to load inside a frame (X-Frame-Options or CSP). Traffic exchanges that frame your link will show it blank.">no frames</span>' : '') + '</div>'
|
||||||
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(d.url) + '</div><div class="muted" style="font-size:11px" data-hl="' + d.id + '">' + esc(healthLine(d)) + '</div></div>'
|
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(d.url) + '</div><div class="muted" style="font-size:11px" data-hl="' + d.id + '">' + esc(healthLine(d)) + '</div></div>'
|
||||||
+ '<div class="wrow"><div class="bar" style="width:70px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + d.weight + '" data-w="' + d.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
|
+ '<div class="wrow"><div class="bar" style="width:70px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + d.weight + '" data-w="' + d.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
|
||||||
@@ -124,8 +126,10 @@
|
|||||||
+ '<span class="tag ' + (d.active ? 'ok' : d.autoPaused ? 'bad' : 'dim') + '">' + (d.active ? 'LIVE' : d.autoPaused ? 'AUTO-PAUSED' : 'PAUSED') + '</span>'
|
+ '<span class="tag ' + (d.active ? 'ok' : d.autoPaused ? 'bad' : 'dim') + '">' + (d.active ? 'LIVE' : d.autoPaused ? 'AUTO-PAUSED' : 'PAUSED') + '</span>'
|
||||||
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-hc="' + d.id + '" title="Hours for this destination" aria-label="Hours for this destination"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></button><button class="btn sm" type="button" data-t="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + d.id + '" aria-label="Remove">×</button></span></div>'
|
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-hc="' + d.id + '" title="Hours for this destination" aria-label="Hours for this destination"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></button><button class="btn sm" type="button" data-t="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + d.id + '" aria-label="Remove">×</button></span></div>'
|
||||||
+ (HE && HE.rid === r.id && HE.did === d.id ? '<div class="rw edit" data-he="' + d.id + '"></div>' : ''); }).join('')
|
+ (HE && HE.rid === r.id && HE.did === d.id ? '<div class="rw edit" data-he="' + d.id + '"></div>' : ''); }).join('')
|
||||||
|
+ (big ? '<div class="rw"><span class="muted">Showing ' + FIRST + ' of ' + r.destinations.length + ' destinations (' + r.destinations.filter(d => d.active).length + ' live).</span> <button class="btn sm" type="button" id="destAll">Show all ' + r.destinations.length + '</button></div>' : '')
|
||||||
: '<div class="rw"><span class="muted">No destinations yet. Add the first page below; until then the link sends people to the fallback.</span></div>';
|
: '<div class="rw"><span class="muted">No destinations yet. Add the first page below; until then the link sends people to the fallback.</span></div>';
|
||||||
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop · health checked every 30 min';
|
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop · health checked every 30 min';
|
||||||
|
if ($('destAll')) $('destAll').addEventListener('click', () => { SHOWALL.add(r.id); renderDest(r); });
|
||||||
const openEditor = did => { const d = r.destinations.find(q => q.id === did); if (!d) return; HE = { rid: r.id, did }; renderDest(r); };
|
const openEditor = did => { const d = r.destinations.find(q => q.id === did); if (!d) return; HE = { rid: r.id, did }; renderDest(r); };
|
||||||
$('destRows').querySelectorAll('[data-hc]').forEach(b => b.addEventListener('click', () => { if (HE && HE.rid === r.id && HE.did === Number(b.dataset.hc)) { HE = null; renderDest(r); } else openEditor(Number(b.dataset.hc)); }));
|
$('destRows').querySelectorAll('[data-hc]').forEach(b => b.addEventListener('click', () => { if (HE && HE.rid === r.id && HE.did === Number(b.dataset.hc)) { HE = null; renderDest(r); } else openEditor(Number(b.dataset.hc)); }));
|
||||||
const heHost = $('destRows').querySelector('[data-he]');
|
const heHost = $('destRows').querySelector('[data-he]');
|
||||||
@@ -234,7 +238,7 @@
|
|||||||
$('hoursChip').addEventListener('click', () => { showTab('hours'); const h = $('rotHours'); if (h.scrollIntoView) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); });
|
$('hoursChip').addEventListener('click', () => { showTab('hours'); const h = $('rotHours'); if (h.scrollIntoView) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); });
|
||||||
$('checkBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const b = $('checkBtn'); b.disabled = true; b.textContent = 'Checking';
|
$('checkBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const b = $('checkBtn'); b.disabled = true; b.textContent = 'Checking';
|
||||||
try { const out = await api('/api/my/rotations/' + r.id + '/health'); const i = ROT.findIndex(x => x.id === r.id); if (i >= 0 && out.rotation) ROT[i] = out.rotation; const fresh = out.rotation || r; renderDest(fresh); select(r.id, true);
|
try { const out = await api('/api/my/rotations/' + r.id + '/health'); const i = ROT.findIndex(x => x.id === r.id); if (i >= 0 && out.rotation) ROT[i] = out.rotation; const fresh = out.rotation || r; renderDest(fresh); select(r.id, true);
|
||||||
const bad = fresh.destinations.filter(d => d.health && (d.health.state === 'dead' || d.health.state === 'parked')).length; toast('Checked ' + fresh.destinations.length + ' destination' + (fresh.destinations.length === 1 ? '' : 's') + (bad ? ', ' + bad + ' failing' : ', all answering')); }
|
if (out.background) { toast('Checking all ' + fresh.destinations.length + ' destinations in the background. Open the link again in a few minutes to see the results.'); } else { const bad = fresh.destinations.filter(d => d.health && (d.health.state === 'dead' || d.health.state === 'parked')).length; toast('Checked ' + fresh.destinations.length + ' destination' + (fresh.destinations.length === 1 ? '' : 's') + (bad ? ', ' + bad + ' failing' : ', all answering')); } }
|
||||||
catch (e) { toast(e.message, true); } b.disabled = false; b.textContent = 'Check now'; });
|
catch (e) { toast(e.message, true); } b.disabled = false; b.textContent = 'Check now'; });
|
||||||
$('pbNew').addEventListener('click', () => pbForm(null));
|
$('pbNew').addEventListener('click', () => pbForm(null));
|
||||||
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
|
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
|
||||||
|
|||||||
+20
-12
@@ -32,7 +32,7 @@
|
|||||||
function tankHoldText(h) {
|
function tankHoldText(h) {
|
||||||
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
|
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
|
||||||
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
|
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
|
||||||
return t;
|
return t + ' Did someone invite you? Tell us in the Who invited you box.';
|
||||||
}
|
}
|
||||||
let TANK_HOLD = null;
|
let TANK_HOLD = null;
|
||||||
function nextMove(d) {
|
function nextMove(d) {
|
||||||
@@ -83,7 +83,9 @@
|
|||||||
{ key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.873 },
|
{ key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.873 },
|
||||||
{ key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.873 },
|
{ key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.873 },
|
||||||
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.873 },
|
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.873 },
|
||||||
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.873 }
|
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.873 },
|
||||||
|
// Founder (2026-11-05): cosmetic, stored on the account, granted at the launch moment to everyone who signed in before it
|
||||||
|
{ key: 'founder', label: 'Founder', sub: 'in before launch', img: '/badges/badge-founder.jpg?v=1', ribbonY: 0.873, extra: true }
|
||||||
];
|
];
|
||||||
let lastMilestones = [];
|
let lastMilestones = [];
|
||||||
function renderBadges(d) {
|
function renderBadges(d) {
|
||||||
@@ -92,12 +94,14 @@
|
|||||||
const strip = $('badgeStrip');
|
const strip = $('badgeStrip');
|
||||||
if (!strip) return;
|
if (!strip) return;
|
||||||
$('badgeCard').hidden = false;
|
$('badgeCard').hidden = false;
|
||||||
strip.innerHTML = BADGES.map(b => {
|
const held = reached.concat(d.founder ? ['founder'] : []);
|
||||||
const got = reached.includes(b.key);
|
strip.innerHTML = BADGES.filter(b => !b.extra || d.founder || d.founderPending).map(b => {
|
||||||
|
const got = held.includes(b.key);
|
||||||
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
|
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
|
||||||
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
|
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
|
||||||
+ '<div class="bl">' + b.label + '</div><div class="bs">' + b.sub + '</div>'
|
+ '<div class="bl">' + b.label + '</div><div class="bs">' + b.sub + '</div>'
|
||||||
+ (got ? '<button class="share" data-badge="' + b.key + '">Share</button> <button class="share" data-badgepost="' + b.key + '" hidden>Post to Telegram</button>' : '<div class="bs">🔒 locked</div>') + '</div>';
|
+ (got ? '<button class="share" data-badge="' + b.key + '">Share</button>' + (b.extra ? '' : ' <button class="share" data-badgepost="' + b.key + '" hidden>Post to Telegram</button>')
|
||||||
|
: b.key === 'founder' ? '<div class="bs">arrives at launch, Sunday Nov 15</div>' : '<div class="bs">🔒 locked</div>') + '</div>';
|
||||||
}).join('');
|
}).join('');
|
||||||
strip.querySelectorAll('[data-badge]').forEach(btn =>
|
strip.querySelectorAll('[data-badge]').forEach(btn =>
|
||||||
btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d)));
|
btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d)));
|
||||||
@@ -603,7 +607,7 @@
|
|||||||
const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0;
|
const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0;
|
||||||
const show = done < items.length && !(at && Date.now() > at + 7 * 86400000);
|
const show = done < items.length && !(at && Date.now() > at + 7 * 86400000);
|
||||||
const lm = $('launchMark');
|
const lm = $('launchMark');
|
||||||
if (lm) { lm.hidden = !show; lm.innerHTML = show ? '<b>Launch ready: ' + done + ' of ' + items.length + '.</b> ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + '<a href="/launch">Open the founding-week checklist</a>' : ''; }
|
if (lm) { lm.hidden = !show; lm.innerHTML = show ? '<b>Launch ready: ' + done + ' of ' + items.length + '.</b> ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + '<a href="/launch">Open the launch week checklist</a>' : ''; }
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
// people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it
|
// people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it
|
||||||
try {
|
try {
|
||||||
@@ -833,12 +837,14 @@
|
|||||||
const tbl = document.createElement('div');
|
const tbl = document.createElement('div');
|
||||||
tbl.className = 'tablewrap';
|
tbl.className = 'tablewrap';
|
||||||
const synN = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisor) || 1)); // network rate (Marty, 2026-10-27, 4:1)
|
const synN = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisor) || 1)); // network rate (Marty, 2026-10-27, 4:1)
|
||||||
|
const synT = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisorText != null ? r.rates.synRateDivisorText : synN) || 1)); // text ads (Marty, 2026-11-12, 1/10)
|
||||||
|
const nOf = c => c.type === 'text' ? synT : synN;
|
||||||
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 on the partner ad network plus views in other members\u2019 zones on their own sites (banner and text ads)' + (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 on the partner ad network plus views in other members\u2019 zones on their own sites (banner and text ads)' + (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]) + '</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]) + '</td>'
|
||||||
+ '<td data-l="Type">' + c.type + (c.type === 'banner' && c.width ? ' <span class="muted small">' + c.width + '×' + c.height + '</span>' : '') + (c.dailyCap ? ' <span class="muted small" title="daily cap: ' + c.dailyCap + ' credits, ' + (c.daySpent || 0) + ' spent today">cap ' + c.dailyCap + '/day</span>' : '') + (c.geo ? ' <span class="muted small" title="shown only to viewers in these country tiers">tier ' + esc(c.geo.replace(/,/g, '+')) + '</span>' : '') + schedChips(c) + '</td>'
|
+ '<td data-l="Type">' + c.type + (c.type === 'banner' && c.width ? ' <span class="muted small">' + c.width + '×' + c.height + '</span>' : '') + (c.dailyCap ? ' <span class="muted small" title="daily cap: ' + c.dailyCap + ' credits, ' + (c.daySpent || 0) + ' spent today">cap ' + c.dailyCap + '/day</span>' : '') + (c.geo ? ' <span class="muted small" title="shown only to viewers in these country tiers">tier ' + esc(c.geo.replace(/,/g, '+')) + '</span>' : '') + schedChips(c) + '</td>'
|
||||||
+ '<td class="num" data-l="Views here">' + c.imps.toLocaleString() + '</td>'
|
+ '<td class="num" data-l="Views here">' + c.imps.toLocaleString() + '</td>'
|
||||||
+ '<td class="num" data-l="Network views">' + (['banner', 'text'].includes(c.type) ? ((c.impsNas || 0) + (c.impsSyn || 0)).toLocaleString() + (synN > 1 && (c.impsNas || c.impsSyn) ? ' <span class="muted small">at 1/' + synN + '</span>' : '') : '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>') + '</td>'
|
+ '<td class="num" data-l="Network views">' + (['banner', 'text'].includes(c.type) ? ((c.impsNas || 0) + (c.impsSyn || 0)).toLocaleString() + (nOf(c) > 1 && (c.impsNas || c.impsSyn) ? ' <span class="muted small">at 1/' + nOf(c) + '</span>' : '') : '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>') + '</td>'
|
||||||
+ '<td class="num" data-l="Clicks">' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '<div class="muted small clk-src" title="where the clicks happened">' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '<span>' + esc(k) + ' ' + v + '</span>').join('') + (c.impsNas ? ' · network: see Network views' : '') + '</div>' : '') + '</td>'
|
+ '<td class="num" data-l="Clicks">' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '<div class="muted small clk-src" title="where the clicks happened">' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '<span>' + esc(k) + ' ' + v + '</span>').join('') + (c.impsNas ? ' · network: see Network views' : '') + '</div>' : '') + '</td>'
|
||||||
+ '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>'
|
+ '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>'
|
||||||
+ '<td data-l="Status">' + (c.status === 'out' ? '<span class="badge amber">budget spent</span>' : c.status === 'done' ? '<span class="muted">ended</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
|
+ '<td data-l="Status">' + (c.status === 'out' ? '<span class="badge amber">budget spent</span>' : c.status === 'done' ? '<span class="muted">ended</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
|
||||||
@@ -1273,7 +1279,7 @@
|
|||||||
const r = await (await fetch('/api/my/tank')).json();
|
const r = await (await fetch('/api/my/tank')).json();
|
||||||
if (r.error) { el.innerHTML = ''; return; }
|
if (r.error) { el.innerHTML = ''; return; }
|
||||||
$('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays;
|
$('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays;
|
||||||
$('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now';
|
$('tankSub').textContent = (r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now') + (r.cap ? ' · you can adopt up to ' + r.cap + ' at a time' : '');
|
||||||
const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : '<span class="badge amber">not yet</span> ' + esc(r.reason);
|
const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : '<span class="badge amber">not yet</span> ' + esc(r.reason);
|
||||||
$('tankMine').innerHTML = r.mine.length ? '<p class="small" style="margin:0 0 6px"><b>Your open adoptions</b></p>' + r.mine.map(m => '<div class="lin-row own"><span class="nm">' + esc(m.name) + '</span>'
|
$('tankMine').innerHTML = r.mine.length ? '<p class="small" style="margin:0 0 6px"><b>Your open adoptions</b></p>' + r.mine.map(m => '<div class="lin-row own"><span class="nm">' + esc(m.name) + '</span>'
|
||||||
+ '<span class="em">' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '</span>'
|
+ '<span class="em">' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '</span>'
|
||||||
@@ -1283,11 +1289,13 @@
|
|||||||
$('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname)));
|
$('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname)));
|
||||||
$('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr)));
|
$('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr)));
|
||||||
if (!r.waiting.length) { el.innerHTML = '<p class="muted small">The tank is empty. Anyone who joins from the public site without a sponsor lands here.</p>'; return; }
|
if (!r.waiting.length) { el.innerHTML = '<p class="muted small">The tank is empty. Anyone who joins from the public site without a sponsor lands here.</p>'; return; }
|
||||||
|
const opens = w => w.opensAt > Date.now(); // new sign-up: they have 24 hours to say who invited them
|
||||||
|
const opensBadge = w => ' <span class="badge amber" title="New member. They have 24 hours from sign-up to tell us who invited them. You can adopt them after that.">Opens in ' + holdLeft(w.opensAt - Date.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>' : '';
|
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.innerHTML = r.waiting.slice().sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0)).map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + readyBadge(w) + '</span>'
|
el.innerHTML = r.waiting.slice().sort((a, b) => (opens(a) ? 1 : 0) - (opens(b) ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0)).map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '</span>'
|
||||||
+ '<span class="em">joined ' + ago(w.joined) + '</span>'
|
+ '<span class="em">joined ' + ago(w.joined) + '</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 ? '<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('');
|
||||||
el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => {
|
el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => {
|
||||||
const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' });
|
const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' });
|
||||||
if (note === null) return;
|
if (note === null) return;
|
||||||
@@ -1547,7 +1555,7 @@
|
|||||||
}
|
}
|
||||||
el.innerHTML = r.levels.map(L => !L.members.length ? '' :
|
el.innerHTML = r.levels.map(L => !L.members.length ? '' :
|
||||||
'<div class="lin-lvl"><div class="cap">Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '</div>'
|
'<div class="lin-lvl"><div class="cap">Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '</div>'
|
||||||
+ L.members.map(m => '<div class="lin-row' + (m.own ? ' own' : '') + '"><span class="nm">' + esc(m.name) + (m.own ? ' <span class="badge">yours</span>' : '') + '</span>'
|
+ L.members.map(m => '<div class="lin-row' + (m.own ? ' own' : '') + '"><span class="nm">' + esc(m.name) + (m.own ? ' <span class="badge">yours</span>' : '') + (m.founder ? ' <span class="badge" title="Founder badge: signed in before LinkSpin launched" style="background:#ffc94d;border-color:#ffc94d;color:#5a3f00">Founder</span>' : '') + '</span>'
|
||||||
+ '<span class="em">' + (m.email ? esc(m.email) : (m.memberId ? '<span class="id">#' + m.memberId + '</span>' : '')) + (m.sponsor ? '<span class="sp">sponsored by ' + esc(m.sponsor) + '</span>' : '') + (m.own ? '' : '<span class="sp">' + (m.bought ? '$25+ buy ✓' : 'no $25+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '</span>') + '</span>'
|
+ '<span class="em">' + (m.email ? esc(m.email) : (m.memberId ? '<span class="id">#' + m.memberId + '</span>' : '')) + (m.sponsor ? '<span class="sp">sponsored by ' + esc(m.sponsor) + '</span>' : '') + (m.own ? '' : '<span class="sp">' + (m.bought ? '$25+ buy ✓' : 'no $25+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '</span>') + '</span>'
|
||||||
+ '<span class="earn' + (m.earnedWei && m.earnedWei !== '0' ? ' on' : '') + '" title="POL this person has paid you so far">'
|
+ '<span class="earn' + (m.earnedWei && m.earnedWei !== '0' ? ' on' : '') + '" title="POL this person has paid you so far">'
|
||||||
+ (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '</span>'
|
+ (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '</span>'
|
||||||
@@ -1584,7 +1592,7 @@
|
|||||||
+ chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '')
|
+ chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '')
|
||||||
+ chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '')
|
+ chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '')
|
||||||
+ chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn')
|
+ chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn')
|
||||||
+ (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '')
|
+ (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus', founder: 'Founder' }[b] || b)).join(' · ')) : '')
|
||||||
+ '<span class="lin-verdict' + (working ? ' on' : '') + '">' + (working ? 'Working' : 'Quiet') + '</span>';
|
+ '<span class="lin-verdict' + (working ? ' on' : '') + '">' + (working ? 'Working' : 'Quiet') + '</span>';
|
||||||
}
|
}
|
||||||
async function loadUplineMessages() {
|
async function loadUplineMessages() {
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// Network sign-in, the sign-in page side (2026-11-12). The SAME file ships in InstantAdPay and LinkSpin (see networksso.js).
|
||||||
|
// On a sign-in screen with no session: ask /api/sso/status once; { check: true } means bounce once through the other site,
|
||||||
|
// which signs the member in here if they are signed in there (the server allows one try per browser per 30 minutes and none
|
||||||
|
// after a sign-out). { hint } means they came from the other site but need the email code here the first time: fill it in.
|
||||||
|
(function () {
|
||||||
|
if (window.__netsso) return; window.__netsso = 1;
|
||||||
|
const BOXES = '#mcEmail,#jnEmail,#siEmail';
|
||||||
|
function fill(email, peer) {
|
||||||
|
let n = 0;
|
||||||
|
const t = setInterval(() => {
|
||||||
|
const el = document.querySelector(BOXES);
|
||||||
|
if (el && el.offsetParent !== null) {
|
||||||
|
clearInterval(t);
|
||||||
|
if (!el.value) el.value = email;
|
||||||
|
if (!document.getElementById('nssoNote')) {
|
||||||
|
const p = document.createElement('p'); p.id = 'nssoNote'; p.className = 'muted small'; p.setAttribute('role', 'note'); p.style.margin = '6px 0';
|
||||||
|
p.textContent = 'Welcome over from ' + peer + '. The first time here, send yourself a code with the same email to finish signing in. After that, ' + peer + ' signs you in here.';
|
||||||
|
(el.closest('label') || el).insertAdjacentElement('afterend', p);
|
||||||
|
}
|
||||||
|
try { el.focus(); } catch (e) {}
|
||||||
|
} else if (++n > 60) clearInterval(t);
|
||||||
|
}, 250);
|
||||||
|
}
|
||||||
|
fetch('/api/sso/status', { credentials: 'same-origin', headers: { Accept: 'application/json' }, cache: 'no-store' })
|
||||||
|
.then(r => r.json()).then(d => {
|
||||||
|
if (!d) return;
|
||||||
|
if (d.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search + location.hash)); return; }
|
||||||
|
if (d.hint) fill(String(d.hint), String(d.peer || 'the other site'));
|
||||||
|
}).catch(() => {});
|
||||||
|
})();
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
CR.tile({ k: 'Bots dropped', v: fmt(t.bots), series: sb, delta: CR.delta(b1, b0, 'vs prior'), note: t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : '' }),
|
CR.tile({ k: 'Bots dropped', v: fmt(t.bots), series: sb, delta: CR.delta(b1, b0, 'vs prior'), note: t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : '' }),
|
||||||
CR.tile({ k: 'Joins', v: fmt(t.joins), note: t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : '' }),
|
CR.tile({ k: 'Joins', v: fmt(t.joins), note: t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : '' }),
|
||||||
CR.tile({ k: 'Buyers', v: fmt(t.purchases), hi: true, note: t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : '' }),
|
CR.tile({ k: 'Buyers', v: fmt(t.purchases), hi: true, note: t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : '' }),
|
||||||
|
CR.tile({ k: 'Goals', v: fmt(t.goals) }),
|
||||||
CR.tile({ k: 'Partner conversions', v: fmt(t.external) }),
|
CR.tile({ k: 'Partner conversions', v: fmt(t.external) }),
|
||||||
// Banner Spin totals beside spin links (2026-10-20)
|
// Banner Spin totals beside spin links (2026-10-20)
|
||||||
CR.tile({ k: 'Banner views', v: fmt(((s.bannerSpins || {}).totals || {}).imps), note: ((s.bannerSpins || {}).count || 0) + ' Banner Spin' + (((s.bannerSpins || {}).count || 0) === 1 ? '' : 's') }),
|
CR.tile({ k: 'Banner views', v: fmt(((s.bannerSpins || {}).totals || {}).imps), note: ((s.bannerSpins || {}).count || 0) + ' Banner Spin' + (((s.bannerSpins || {}).count || 0) === 1 ? '' : 's') }),
|
||||||
@@ -34,7 +35,9 @@
|
|||||||
const hmax = Math.max(1, ...(s.hours || [])); $('hourBars').innerHTML = (s.hours || []).map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 UTC · ' + n + '"></i>').join('');
|
const hmax = Math.max(1, ...(s.hours || [])); $('hourBars').innerHTML = (s.hours || []).map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 UTC · ' + n + '"></i>').join('');
|
||||||
const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00');
|
const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00');
|
||||||
$('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.';
|
$('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.';
|
||||||
$('convRows').innerHTML = kv(s.conversions || [], 0);
|
// one list (2026-11-07): site and network events first, then goals, a value beside anything that has one
|
||||||
|
const CONV_NAME = { join: 'Joins', lead: 'Leads', wallet: 'Wallets', purchase: 'Purchases', external: 'Partner postbacks' };
|
||||||
|
$('convRows').innerHTML = kv((s.conversions || []).map(x => ({ k: (CONV_NAME[x.k] || String(x.k).replace(/^goal:\s*/, 'Goal: ')) + (x.value ? ' \u00b7 $' + Number(x.value).toFixed(2) : ''), n: x.n })), 0);
|
||||||
// -- Pages and Zones (2026-10-10): one bar per Central day in the range (empty days are zero), totals, per-item table
|
// -- Pages and Zones (2026-10-10): one bar per Central day in the range (empty days are zero), totals, per-item table
|
||||||
const dayBars = (barsId, axisId, rows, f, g, empty) => {
|
const dayBars = (barsId, axisId, rows, f, g, empty) => {
|
||||||
const map = {}; (rows || []).forEach(r => { map[r.day] = r; });
|
const map = {}; (rows || []).forEach(r => { map[r.day] = r; });
|
||||||
|
|||||||
@@ -17,11 +17,15 @@
|
|||||||
ms.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0));
|
ms.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0));
|
||||||
return ms;
|
return ms;
|
||||||
}
|
}
|
||||||
|
// where a direct came from + how they joined (2026-11-13): src = first-touch referrer with the link's ?src= tag, via = the path
|
||||||
|
const VIA_LABEL = { carried: 'came over from InstantAdPay', btc4hits: 'moved over from BTC4Hits', direct: 'your invite link', stack: 'Stack POL', zones: 'an ad zone', tank: 'adopted from the holding tank' };
|
||||||
|
const srcLabel = s => !s ? '' : s === 'direct' ? 'no referring site' : s === 'network' ? 'InstantAdPay' : /^legacy:/.test(s) ? s.split(':')[1] : s;
|
||||||
|
const originText = m => { const a = srcLabel(m.src), b = m.via ? (VIA_LABEL[m.via] || ('link "' + m.via + '"')) : ''; return (a ? 'from ' + a : '') + (a && b ? ' · ' : '') + (b ? 'via ' + b : ''); };
|
||||||
function render() {
|
function render() {
|
||||||
const ms = rows(); const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); const total = L ? L.members.length : 0;
|
const ms = rows(); const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); const total = L ? L.members.length : 0;
|
||||||
$('rows').innerHTML = ms.length ? ms.map(m => { const today = (m.lastSeen || 0) >= dayStart();
|
$('rows').innerHTML = ms.length ? ms.map(m => { const today = (m.lastSeen || 0) >= dayStart();
|
||||||
const sg = stageOf(m), q = quiet(m);
|
const sg = stageOf(m), q = quiet(m);
|
||||||
return '<div class="rw st-row' + (q ? ' stalled' : '') + '" data-st="' + sg + '"><div><b>' + esc(m.name) + (m.own ? ' <span class="tag dim">YOURS</span>' : '') + '</b><br><span class="mono muted" style="font-size:11px">' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $25+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '</span></div>'
|
return '<div class="rw st-row' + (q ? ' stalled' : '') + '" data-st="' + sg + '"><div><b>' + esc(m.name) + (m.own ? ' <span class="tag dim">YOURS</span>' : '') + (m.founder ? ' <span class="tag" title="Founder badge: signed in before LinkSpin launched" style="background:#ffc94d;color:#5a3f00">FOUNDER</span>' : '') + '</b><br><span class="mono muted" style="font-size:11px">' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $25+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '</span>' + (m.email && !m.own ? '<br><span class="mono" style="font-size:11.5px;word-break:break-all">' + esc(m.email) + '</span>' : '') + (!m.own && originText(m) ? '<br><span class="muted" style="font-size:11.5px">' + esc(originText(m)) + '</span>' : '') + '</div>'
|
||||||
+ '<span class="mono ' + (today ? 'ok' : (m.lastSeen && Date.now() - m.lastSeen > 3 * 86400e3 ? 'warn' : '')) + '" style="font-size:12px">' + (today ? 'today' : ago(m.lastSeen)) + '</span>'
|
+ '<span class="mono ' + (today ? 'ok' : (m.lastSeen && Date.now() - m.lastSeen > 3 * 86400e3 ? 'warn' : '')) + '" style="font-size:12px">' + (today ? 'today' : ago(m.lastSeen)) + '</span>'
|
||||||
+ '<span><span class="stg" data-st="' + sg + '">' + STAGE[sg] + '</span>' + (q ? '<br><span class="stg quiet">' + (m.lastSeen ? 'quiet ' + Math.floor((Date.now() - m.lastSeen) / 86400e3) + 'd' : 'never signed in') + '</span>' : '') + '</span>'
|
+ '<span><span class="stg" data-st="' + sg + '">' + STAGE[sg] + '</span>' + (q ? '<br><span class="stg quiet">' + (m.lastSeen ? 'quiet ' + Math.floor((Date.now() - m.lastSeen) / 86400e3) + 'd' : 'never signed in') + '</span>' : '') + '</span>'
|
||||||
+ '<span class="r num">' + (m.earnedWei && m.earnedWei !== '0' ? '+' + pol(m.earnedWei) + ' POL' : '<span class="muted">0</span>') + '</span>'
|
+ '<span class="r num">' + (m.earnedWei && m.earnedWei !== '0' ? '+' + pol(m.earnedWei) + ' POL' : '<span class="muted">0</span>') + '</span>'
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// The Founder badge on a member's wall (2026-11-05, cosmetic). Kept apart from wall.js, which a shared policy test pins by version.
|
||||||
|
(async function () {
|
||||||
|
const img = document.getElementById('bioFounder'); if (!img) return;
|
||||||
|
const name = location.pathname.split('/').pop();
|
||||||
|
try {
|
||||||
|
const w = await (await fetch('/api/wall/' + encodeURIComponent(name))).json();
|
||||||
|
if (w && w.founder && w.founder.img) { img.src = w.founder.img; img.title = 'Founder badge: signed in before LinkSpin launched'; img.hidden = false; }
|
||||||
|
} catch (e) {}
|
||||||
|
})();
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 154 KiB |
@@ -121,6 +121,7 @@
|
|||||||
<li class="f-win"><span class="k">5</span><b>Counted in Conversions</b>Against the ad, spin link, page and source that sent them, with cost per goal.</li>
|
<li class="f-win"><span class="k">5</span><b>Counted in Conversions</b>Against the ad, spin link, page and source that sent them, with cost per goal.</li>
|
||||||
</ol>
|
</ol>
|
||||||
<p class="muted" style="font-size:13px">The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere. An ad click and the spin-link click it led to count as one click.</p>
|
<p class="muted" style="font-size:13px">The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere. An ad click and the spin-link click it led to count as one click.</p>
|
||||||
|
<p class="muted" style="font-size:13px"><b>Sending people to LinkSpin or InstantAdPay?</b> Those two count by themselves, with no goal and no pixel. The landing tag adds the click id to your links to either site, also when the address sits inside a redirect link of your own. A spin link or Banner Spin pointed straight at either site carries it too. Then their sign-up, wallet link and each package they buy within 30 days of the click show in <a href="/reports">Reports</a> under Conversions, purchases with their USD price. This is reporting only. It never changes who a sponsor is or what anyone is paid.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -227,6 +228,7 @@
|
|||||||
<tr><td>Cookie</td><td>Exact, through LinkSpin's own cookie. Some browsers block it.</td></tr>
|
<tr><td>Cookie</td><td>Exact, through LinkSpin's own cookie. Some browsers block it.</td></tr>
|
||||||
<tr><td>24 h match</td><td>The same network and browser within a day of the click. A good guess, not proof.</td></tr>
|
<tr><td>24 h match</td><td>The same network and browser within a day of the click. A good guess, not proof.</td></tr>
|
||||||
<tr><td>Test / last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</td></tr>
|
<tr><td>Test / last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</td></tr>
|
||||||
|
<tr><td>Joins, wallets, purchases</td><td>In Reports, under Conversions, beside your goals. People who came through your click and signed up, linked a wallet or bought a package on LinkSpin or InstantAdPay. A sign-up and a wallet count once per click, every package counts on its own with its USD price, all within 30 days of the click. Your own account is left out.</td></tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<div class="pb" style="border-top:1px solid var(--line)"><p class="muted" style="font-size:13px">Each goal gets its own report: by ad campaign (LinkSpin and InstantAdPay), by spin link, by Banner Spin, by destination page and by traffic source (a source you named under Sources, or else the referring site or ad placement). Press CSV for every conversion with its time in Central time, goal, value, match method, campaign, spin link, page, source, country and device. The counting rules: each goal counts once per click, only within 30 days of a real click, and only for clicks on your own ads, links and Banner Spins. Your own clicks on any of them (made while signed in, or from a browser you sign in from) are kept as tests: the note at the top of "How sure is each count" says how many.</p></div>
|
<div class="pb" style="border-top:1px solid var(--line)"><p class="muted" style="font-size:13px">Each goal gets its own report: by ad campaign (LinkSpin and InstantAdPay), by spin link, by Banner Spin, by destination page and by traffic source (a source you named under Sources, or else the referring site or ad placement). Press CSV for every conversion with its time in Central time, goal, value, match method, campaign, spin link, page, source, country and device. The counting rules: each goal counts once per click, only within 30 days of a real click, and only for clicks on your own ads, links and Banner Spins. Your own clicks on any of them (made while signed in, or from a browser you sign in from) are kept as tests: the note at the top of "How sure is each count" says how many.</p></div>
|
||||||
@@ -258,7 +260,8 @@
|
|||||||
<div><dt>Will the tags slow down or break my page?</dt><dd>No. Both load in the background, never stop your page from showing and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.</dd></div>
|
<div><dt>Will the tags slow down or break my page?</dt><dd>No. Both load in the background, never stop your page from showing and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.</dd></div>
|
||||||
<div><dt>Do I need a separate goal for each link or ad?</dt><dd>No. One goal covers every ad and spin link you own. Each conversion is counted against whichever click sent that visitor.</dd></div>
|
<div><dt>Do I need a separate goal for each link or ad?</dt><dd>No. One goal covers every ad and spin link you own. Each conversion is counted against whichever click sent that visitor.</dd></div>
|
||||||
<div><dt>I advertise on InstantAdPay too. Do I set it up twice?</dt><dd>No. Your InstantAdPay goals are these same goals, held on your LinkSpin account under the same email. One landing tag and one goal pixel count clicks from both sites.</dd></div>
|
<div><dt>I advertise on InstantAdPay too. Do I set it up twice?</dt><dd>No. Your InstantAdPay goals are these same goals, held on your LinkSpin account under the same email. One landing tag and one goal pixel count clicks from both sites.</dd></div>
|
||||||
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent.</dd></div>
|
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent. When someone joins InstantAdPay on your click, the two sites match the event to your click server to server, and your reports show counts and values, never who the person is.</dd></div>
|
||||||
|
<div><dt>Why does a sign-up I sent not show?</dt><dd>The click has to reach the join page. Check that your landing tag is on the page and the link is a real link (a button that only runs a script cannot carry it), and that the visitor opened it from your click within the last 30 days. People who joined before this was switched on on 2026-11-07 cannot be matched afterwards.</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
<div class="two">
|
<div class="two">
|
||||||
<div class="panel">
|
<div class="panel">
|
||||||
<h2>Set it up in 3 steps</h2>
|
<h2>Set it up in 3 steps</h2>
|
||||||
|
<div class="muted" style="margin:2px 0 6px">Goals show here with their cost. <a href="/reports">Reports</a> shows everything in one list: goals, plus joins, wallets and purchases on LinkSpin and InstantAdPay.</div>
|
||||||
<div style="margin:2px 0 6px"><a href="/conversion-tracking" target="_blank" rel="noopener">How to set it up: the step-by-step guide with copy-paste examples (WordPress, page builders, Aweber, GetResponse)</a></div>
|
<div style="margin:2px 0 6px"><a href="/conversion-tracking" target="_blank" rel="noopener">How to set it up: the step-by-step guide with copy-paste examples (WordPress, page builders, Aweber, GetResponse)</a></div>
|
||||||
<ol class="steps">
|
<ol class="steps">
|
||||||
<li><b>Landing page:</b> paste the landing tag once, before </body>. It keeps the click id on your own site for 30 days.</li>
|
<li><b>Landing page:</b> paste the landing tag once, before </body>. It keeps the click id on your own site for 30 days.</li>
|
||||||
@@ -69,7 +70,7 @@
|
|||||||
<div id="goalReports"></div>
|
<div id="goalReports"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/conversions.js?v=20261026a"></script>
|
<script src="/assets/conversions.js?v=20261026a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+4
-4
@@ -81,10 +81,10 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/credits-screen.js?v=20261101t"></script>
|
<script src="/assets/credits-screen.js?v=20261107tg"></script>
|
||||||
<script src="/assets/fuel.js?v=20261025ff"></script>
|
<script src="/assets/fuel.js?v=20261112sso"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -69,6 +69,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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@
|
|||||||
<div id="page">
|
<div id="page">
|
||||||
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
|
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/help-screen.js?v=20261016a"></script>
|
<script src="/assets/help-screen.js?v=20261016a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+3
-3
@@ -117,13 +117,13 @@
|
|||||||
<article id="pages" class="tile card">
|
<article id="pages" class="tile card">
|
||||||
<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/></svg>
|
<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/></svg>
|
||||||
<h3 class="disp">Pages</h3>
|
<h3 class="disp">Pages</h3>
|
||||||
<p>Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: list, CSV, webhook.</p>
|
<p>Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: your own list and a CSV download, or paste your autoresponder form.</p>
|
||||||
<div class="foot-row"><span class="tag t">bridge</span><span class="tag t">review</span><span class="tag t">squeeze</span><span class="tag ok">leads: yours</span></div>
|
<div class="foot-row"><span class="tag t">bridge</span><span class="tag t">review</span><span class="tag t">squeeze</span><span class="tag ok">leads: yours</span></div>
|
||||||
</article>
|
</article>
|
||||||
<article id="zones" class="tile card">
|
<article id="zones" class="tile card">
|
||||||
<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>
|
<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>
|
||||||
<h3 class="disp">Zones</h3>
|
<h3 class="disp">Zones</h3>
|
||||||
<p>One script tag puts an ad slot on your own site. It shows member ads first, then network ads, and pays you ad credits for every viewable impression. Five sizes.</p>
|
<p>One script tag puts an ad slot on your own site. It shows member ads first, then network ads, and pays you ad credits for every viewable impression. Nine sizes.</p>
|
||||||
<div class="foot-row"><span class="tag">728×90</span><span class="tag">300×250</span><span class="tag">160×600</span><span class="tag">468×60</span><span class="tag">320×50</span></div>
|
<div class="foot-row"><span class="tag">728×90</span><span class="tag">300×250</span><span class="tag">160×600</span><span class="tag">468×60</span><span class="tag">320×50</span></div>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
@@ -224,6 +224,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script src="/assets/home.js?v=20261007a"></script>
|
<script src="/assets/home.js?v=20261113me"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -106,7 +106,7 @@ body.squeeze .card{position:sticky;top:16px}
|
|||||||
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/join.js?v=20261009b"></script>
|
<script src="/assets/join.js?v=20261111b4h"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+19
-22
@@ -2,8 +2,8 @@
|
|||||||
<html lang="en" data-theme-base="dark">
|
<html lang="en" data-theme-base="dark">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
<title>Founding week checklist | LinkSpin</title>
|
<title>Launch week checklist | LinkSpin</title>
|
||||||
<meta name="description" content="The eight things a leader gets done before launch, and why the order matters. Member training.">
|
<meta name="description" content="LinkSpin opens to the world on Sunday, November 15 at 6 AM Central. The eight things to get done before then, and why the order matters.">
|
||||||
<meta name="robots" content="noindex">
|
<meta name="robots" content="noindex">
|
||||||
<meta name="theme-color" content="#043b2f">
|
<meta name="theme-color" content="#043b2f">
|
||||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"light",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("ls.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.LSTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("ls.theme",c);else localStorage.removeItem("ls.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("ls-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"light",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("ls.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.LSTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("ls.theme",c);else localStorage.removeItem("ls.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("ls-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||||
@@ -52,9 +52,10 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<section class="hero" style="padding:70px 0 20px">
|
<section class="hero" style="padding:70px 0 20px">
|
||||||
<p class="eyebrow">Leaders · founding week</p>
|
<p class="eyebrow">Launch week · Sunday, November 15, 6 AM Central</p>
|
||||||
<h1>Eight things before <em>launch day</em>.</h1>
|
<h1>Eight things before <em>Sunday</em>.</h1>
|
||||||
<p class="lead">Get these done this week, in this order, and your first commissions land in your wallet instead of climbing past you. Everything here reads from your live account.</p>
|
<p class="lead">LinkSpin is open for pre-launch now and opens to the world on Sunday, November 15 at 6 AM Central. Get these done before then, in this order, so your line is set up when everyone else arrives. Everything here reads from your live account.</p>
|
||||||
|
<div class="lw-rule" style="margin-top:18px"><b>New for launch week</b>Founder badge: every account that signs in at least once before Sunday, November 15 at 6 AM Central gets the Founder badge on launch morning. It shows on your badges, your wall, your sponsor's Team list and the leaderboard. It is a badge only, nothing else comes with it. Launch week contest: from Sunday, November 15 at 6 AM through Saturday, November 21 at 11:59 PM Central, the <a href="/leaderboard">leaderboard</a> ranks members by packages bought by the people they sponsor directly (at least 2 to place). The top 3 win POL, paid to the wallet on file after the week closes. Prize details are on the leaderboard from launch morning.</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div class="card" id="gate"><h3>Members only</h3><p class="muted small">Sign in to your member area to open the checklist. <a href="/links">Sign in</a></p></div>
|
<div class="card" id="gate"><h3>Members only</h3><p class="muted small">Sign in to your member area to open the checklist. <a href="/links">Sign in</a></p></div>
|
||||||
@@ -75,29 +76,25 @@
|
|||||||
|
|
||||||
<h2>The week, day by day</h2>
|
<h2>The week, day by day</h2>
|
||||||
<div class="days">
|
<div class="days">
|
||||||
<div><div class="k">Day 1</div><ul><li>Items 1 to 3 done in one sitting.</li><li>Decide your play, and whether you are going for level 2 or all three.</li></ul></div>
|
<div><div class="k">Today</div><ul><li>Items 1 to 3 done in one sitting.</li><li>Decide your play, and whether you are going for level 2 or all three.</li></ul></div>
|
||||||
<div><div class="k">Days 2 to 3</div><ul><li>Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.</li><li>Line banner uploaded.</li></ul></div>
|
<div><div class="k">This week</div><ul><li>Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.</li><li>Line banner uploaded.</li></ul></div>
|
||||||
<div><div class="k">Days 4 to 6</div><ul><li>Place your first two personally.</li><li>Walk them through items 1 to 3 on their accounts.</li></ul></div>
|
<div><div class="k">By Saturday, Nov 14</div><ul><li>Place your first two personally.</li><li>Walk them through items 1 to 3 on their accounts.</li></ul></div>
|
||||||
<div><div class="k">Launch day</div><ul><li>Everyone releases links at the same time.</li><li>Watch the ledger and the Telegram proof feed fill.</li></ul></div>
|
<div><div class="k">Sunday, Nov 15</div><ul><li>6 AM Central: everyone shares their link at the same time.</li><li>The launch week contest runs through Saturday, Nov 21.</li></ul></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2>What to send your two this week</h2>
|
<h2>What to send your two this week</h2>
|
||||||
<blockquote><span>Text or DM · before launch</span>I'm bringing a small group in early on something before it opens publicly next week. Free to join, real advertising, and every payment lands in your own wallet the second it happens. I want you positioned before the doors open. Set up takes five minutes: <span data-link>your link</span></blockquote>
|
<blockquote><span>Text or DM · before launch</span>I'm bringing a small group in early on something before it opens to everyone on Sunday, November 15. Free with an email: one link that rotates every page you promote, a bridge page builder, and an ad slot for your site that pays ad credits. Join before Sunday and you are on my team. Set up takes five minutes: <span data-link>your link</span></blockquote>
|
||||||
<blockquote><span>Text or DM · after they join</span>Three quick things before launch so your first commission lands with you and not past you: pick your username, link your wallet, switch on payouts. All on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.</blockquote>
|
<blockquote><span>Text or DM · after they join</span>Three quick things before Sunday so your first commission lands with you and not past you: pick your username and link your wallet (payouts then switch on by themselves, LinkSpin pays the gas). Both on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.</blockquote>
|
||||||
|
|
||||||
<h2 id="share">Launch graphics and posts</h2>
|
<h2 id="share">Launch posts</h2>
|
||||||
<p class="small muted" style="margin:0 0 10px">Two images, no text on them but the headline, so they work anywhere. Post one with the day's line below it; your link and the FOUNDER code are already in each line.</p>
|
<p class="small muted" style="margin:0 0 10px">Ready-to-share posts with your invite link already in them. Copy one and paste it where your people are.</p>
|
||||||
<div class="lg-imgs">
|
|
||||||
<figure><img src="/banners/iap-launch-doors-1200x630.jpg" alt="Doors open Monday" loading="lazy"><figcaption>Wide, 1200x630 · for X, Facebook, LinkedIn, link previews <a href="/banners/iap-launch-doors-1200x630.jpg" download>Download</a></figcaption></figure>
|
|
||||||
<figure><img src="/banners/iap-launch-doors-1080x1080.jpg" alt="Doors open Monday" loading="lazy"><figcaption>Square, 1080x1080 · for Instagram, Telegram, WhatsApp <a href="/banners/iap-launch-doors-1080x1080.jpg" download>Download</a></figcaption></figure>
|
|
||||||
</div>
|
|
||||||
<div id="postList"></div>
|
<div id="postList"></div>
|
||||||
|
|
||||||
<h2 id="swipes">Launch week swipes: four emails for your list</h2>
|
<h2 id="swipes">Launch emails for your list</h2>
|
||||||
<p class="small muted" style="margin:0 0 10px">Send one a day to your own list or contacts, in this order. Your invite link and the FOUNDER code (500 free credits for anyone who joins before Monday 9 AM Central) are already filled in. Copy, paste, send from your own email. Edit anything you like.</p>
|
<p class="small muted" style="margin:0 0 10px">Send from your own email to your own list or contacts. Your invite link is already filled in. Edit anything you like.</p>
|
||||||
<div id="swipeList"></div>
|
<div id="swipeList"></div>
|
||||||
|
|
||||||
<p class="small muted" style="margin:26px 0 0">No income is guaranteed. Results depend on your effort. Crypto carries risk of loss. LinkSpin sells advertising; it is not an investment.</p>
|
<p class="small muted" style="margin:26px 0 0">Ad credits buy advertising, not income. Payouts come only from purchases in your line. Cryptocurrency involves risk of loss. LinkSpin sells advertising; it is not an investment.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
@@ -105,7 +102,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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/launch.js?v=20260915b"></script>
|
<script src="/assets/launch.js?v=20261105po"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -65,7 +65,7 @@
|
|||||||
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/ledger.js?v=20261007a"></script>
|
<script src="/assets/ledger.js?v=20261007a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+20
-3
@@ -85,6 +85,23 @@
|
|||||||
.tierbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}
|
.tierbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}
|
||||||
.modes{display:grid;gap:8px} .modes label{display:flex;gap:8px;align-items:flex-start;cursor:pointer} .modes input{margin-top:3px}
|
.modes{display:grid;gap:8px} .modes label{display:flex;gap:8px;align-items:flex-start;cursor:pointer} .modes input{margin-top:3px}
|
||||||
.bsr .ml{display:none}
|
.bsr .ml{display:none}
|
||||||
|
/* Same as .dest: switch on the TABLE's width, not the window's. Beside the link list and the rail a desktop window left the
|
||||||
|
banner column a few letters wide (Marty, 11-04: "the data is all in the left column"). */
|
||||||
|
.tbl.bsr,.tbl.st3{container-type:inline-size}
|
||||||
|
@container (max-width:860px){
|
||||||
|
.bsr .hd{display:none}
|
||||||
|
.bsr .ml{display:inline;color:var(--muted);font-size:11px}
|
||||||
|
.bsr .rw:not(.edit){grid-template-columns:repeat(auto-fit,minmax(110px,1fr))}
|
||||||
|
.bsr .rw:not(.edit)>:first-child{grid-column:1/-1}
|
||||||
|
.bsr .rw .r{text-align:left}
|
||||||
|
}
|
||||||
|
@container (max-width:640px){
|
||||||
|
.st3 .hd{display:none}
|
||||||
|
.st3 .ml{display:inline;color:var(--muted);font-size:11px}
|
||||||
|
.st3 .rw{grid-template-columns:1fr 1fr 1fr}
|
||||||
|
.st3 .rw>:first-child{grid-column:1/-1}
|
||||||
|
.st3 .rw .r{text-align:left}
|
||||||
|
}
|
||||||
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 80px 70px 70px 64px 74px 56px}
|
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 80px 70px 70px 64px 74px 56px}
|
||||||
.st3 .ml{display:none} .bhl{font-size:11.5px} .bswin{background:var(--ok);color:var(--ok-ink);border-radius:3px;padding:1px 6px;font-size:10px;font-weight:700;letter-spacing:.06em;margin-left:6px;vertical-align:middle}
|
.st3 .ml{display:none} .bhl{font-size:11.5px} .bswin{background:var(--ok);color:var(--ok-ink);border-radius:3px;padding:1px 6px;font-size:10px;font-weight:700;letter-spacing:.06em;margin-left:6px;vertical-align:middle}
|
||||||
.bscache{display:block;margin-top:3px;font-size:11px;color:var(--warn)} .bsbreak{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
.bscache{display:block;margin-top:3px;font-size:11px;color:var(--warn)} .bsbreak{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
||||||
@@ -253,8 +270,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/links.js?v=20261021t"></script>
|
<script src="/assets/links.js?v=20261111big"></script>
|
||||||
<script src="/assets/banner-spin.js?v=20261020bs3"></script>
|
<script src="/assets/banner-spin.js?v=20261105sz"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+4
-4
@@ -280,7 +280,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="card" id="tankCard">
|
<div class="card" id="tankCard">
|
||||||
<div class="card-head"><h3>Holding tank</h3><span class="sub" id="tankSub">members who arrived with no sponsor</span></div>
|
<div class="card-head"><h3>Holding tank</h3><span class="sub" id="tankSub">members who arrived with no sponsor</span></div>
|
||||||
<p class="muted small">People who joined without a sponsor wait here. Adopt one and you become their sponsor: a chat opens, they get an email with your message, and their first purchase binds to you on the contract. First come. At most <b id="tankCap">2</b> open adoptions at a time, and an adoption goes back to the tank after <b id="tankTtl">7</b> days if they have not linked a wallet or bought.</p>
|
<p class="muted small">People who joined without a sponsor wait here. New sign-ups open for adoption 24 hours after they join, so they have time to tell us who invited them. Adopt one and you become their sponsor: a chat opens, they get an email with your message, and their first purchase binds to you on the contract. First come. At most <b id="tankCap">2</b> open adoptions at a time, and an adoption goes back to the tank after <b id="tankTtl">7</b> days if they have not linked a wallet or bought.</p>
|
||||||
<p class="small" id="tankWhy" hidden></p>
|
<p class="small" id="tankWhy" hidden></p>
|
||||||
<div id="tankMine"></div>
|
<div id="tankMine"></div>
|
||||||
<div id="tankList"><p class="muted small">Loading…</p></div>
|
<div id="tankList"><p class="muted small">Loading…</p></div>
|
||||||
@@ -1015,12 +1015,12 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/tools.js?v=20261011a"></script>
|
<script src="/assets/tools.js?v=20261011a"></script>
|
||||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||||
<script src="/assets/promo.js?v=20261020bs3"></script>
|
<script src="/assets/promo.js?v=20261020bs3"></script>
|
||||||
<script src="/assets/my.js?v=20261101t"></script>
|
<script src="/assets/my.js?v=20261112txt"></script>
|
||||||
<script src="/assets/chat.js?v=20261016a"></script>
|
<script src="/assets/chat.js?v=20261016a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -73,7 +73,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/pages-screen.js?v=20261021t"></script>
|
<script src="/assets/pages-screen.js?v=20261021t"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -131,7 +131,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 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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/partners.js?v=20261010a"></script>
|
<script src="/assets/partners.js?v=20261010a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -193,7 +193,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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/plays.js?v=20260910b"></script>
|
<script src="/assets/plays.js?v=20260910b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@
|
|||||||
<p>When someone opens one of your spin links or sees a zone on your site, we record the time, the destination chosen, the country, the device type, the referring site and any click id or tracking parameters in the link, plus a daily-salted hash of the visitor that is not reversible to a person. These records power your reports and are kept for the life of the link.</p>
|
<p>When someone opens one of your spin links or sees a zone on your site, we record the time, the destination chosen, the country, the device type, the referring site and any click id or tracking parameters in the link, plus a daily-salted hash of the visitor that is not reversible to a person. These records power your reports and are kept for the life of the link.</p>
|
||||||
<h2 class="disp">Conversion tracking</h2>
|
<h2 class="disp">Conversion tracking</h2>
|
||||||
<p>When someone clicks an ad on LinkSpin or InstantAdPay, or a spin link whose owner tracks goals, we give that click a random click id and add it to the address they land on (as <code>lsclk</code>). We keep the click with its time, campaign, country, device type and where it was clicked, plus a one-way hash of the network address and browser that we use only to match a conversion within 24 hours. We do not store the IP address itself.</p>
|
<p>When someone clicks an ad on LinkSpin or InstantAdPay, or a spin link whose owner tracks goals, we give that click a random click id and add it to the address they land on (as <code>lsclk</code>). We keep the click with its time, campaign, country, device type and where it was clicked, plus a one-way hash of the network address and browser that we use only to match a conversion within 24 hours. We do not store the IP address itself.</p>
|
||||||
<p>Advertisers who use our landing tag (<code>t.js</code>) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named <code>ls_clk</code> on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (<code>cv.gif</code> or <code>cv.js</code>) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named <code>ls.clk</code> on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click.</p>
|
<p>Advertisers who use our landing tag (<code>t.js</code>) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named <code>ls_clk</code> on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (<code>cv.gif</code> or <code>cv.js</code>) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named <code>ls.clk</code> on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click. The tag also adds the click id to links to LinkSpin and InstantAdPay. If you then join InstantAdPay, it keeps the click id with your account and tells LinkSpin about your sign-up, wallet link and package purchases on that click, so the owner of the click sees counts and values in their reports, never who you are.</p>
|
||||||
<h2 class="disp">Leads on your pages</h2>
|
<h2 class="disp">Leads on your pages</h2>
|
||||||
<p>Email addresses entered on a page you publish belong to you and are shown only to you. We store them so you can download them or forward them to your own autoresponder. Visitors are told on the page who is collecting their email.</p>
|
<p>Email addresses entered on a page you publish belong to you and are shown only to you. We store them so you can download them or forward them to your own autoresponder. Visitors are told on the page who is collecting their email.</p>
|
||||||
<h2 class="disp">What we do not collect</h2>
|
<h2 class="disp">What we do not collect</h2>
|
||||||
|
|||||||
+3
-3
@@ -42,7 +42,7 @@
|
|||||||
<div style="display:grid;gap:16px;align-content:start">
|
<div style="display:grid;gap:16px;align-content:start">
|
||||||
<div class="panel"><h2>Top links</h2><div class="tbl top"><div class="hd"><span>Link</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">Conv.</span></div><div id="topRows"></div></div></div>
|
<div class="panel"><h2>Top links</h2><div class="tbl top"><div class="hd"><span>Link</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">Conv.</span></div><div id="topRows"></div></div></div>
|
||||||
<div class="panel"><h2>Your best hours</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr));height:80px"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted" id="hourNote"></div></div>
|
<div class="panel"><h2>Your best hours</h2><div class="bars" id="hourBars" style="grid-template-columns:repeat(24,minmax(0,1fr));height:80px"></div><div class="axis"><span>00</span><span>06</span><span>12</span><span>18</span><span>23</span></div><div class="muted" id="hourNote"></div></div>
|
||||||
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback. Your own goals (subscribers, sales) and cost per goal are on <a href="/conversions">Conversions</a>.</div></div>
|
<div class="panel"><h2>Conversions</h2><div class="kv" id="convRows"></div><div class="muted">Everything your clicks led to, each event once: your goals, plus joins, wallets and package purchases on LinkSpin and InstantAdPay, and anything a partner reported by postback. People count when they arrive on a click of yours, through your landing tag or a spin link pointed straight at either site, within 30 days of the click. Your own account and own clicks are left out. Set up goals and see cost per goal on <a href="/conversions">Conversions</a>.</div></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Pages: views, uniques, clicks through and leads on the member's bridge / review / squeeze pages (2026-10-10) -->
|
<!-- Pages: views, uniques, clicks through and leads on the member's bridge / review / squeeze pages (2026-10-10) -->
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/reports.js?v=20261020bs3"></script>
|
<script src="/assets/reports.js?v=20261107nc"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -128,7 +128,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
||||||
<script src="/assets/sources-screen.js?v=20261028a"></script>
|
<script src="/assets/sources-screen.js?v=20261028a"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+1
-1
@@ -67,7 +67,7 @@
|
|||||||
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
<span class="mono" style="font-size:11px">a Crypto Team Build Network property</span>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/support.js?v=20261016a"></script>
|
<script src="/assets/support.js?v=20261016a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+37
-2
@@ -2,7 +2,8 @@
|
|||||||
* <script async src="https://linkspin.app/t.js?px=YOUR_PIXEL_ID"></script>
|
* <script async src="https://linkspin.app/t.js?px=YOUR_PIXEL_ID"></script>
|
||||||
* It reads the click id LinkSpin or InstantAdPay put on the link (lsclk, lsid or clickid in the address), keeps it on YOUR
|
* It reads the click id LinkSpin or InstantAdPay put on the link (lsclk, lsid or clickid in the address), keeps it on YOUR
|
||||||
* site for 30 days (localStorage + a first-party cookie, both named ls_clk), copies it into hidden form fields named lsclk,
|
* site for 30 days (localStorage + a first-party cookie, both named ls_clk), copies it into hidden form fields named lsclk,
|
||||||
* lsid or clickid, and adds it to links that stay on your site. Nothing personal is read or stored.
|
* lsid or clickid, and adds it to links that stay on your site. Links to InstantAdPay and LinkSpin carry it too, also inside a
|
||||||
|
* redirect link of your own, so a sign-up or purchase there is counted on your click. Nothing personal is read or stored.
|
||||||
* It never throws and never blocks your page: every step is wrapped, and it only runs after the page has its scripts.
|
* It never throws and never blocks your page: every step is wrapped, and it only runs after the page has its scripts.
|
||||||
*/
|
*/
|
||||||
(function () {
|
(function () {
|
||||||
@@ -65,7 +66,41 @@
|
|||||||
u.searchParams.set('lsclk', id); a.href = u.toString();
|
u.searchParams.set('lsclk', id); a.href = u.toString();
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a) decorate(a); } catch (er) {} }
|
// links to the network (2026-11-07): a bridge page's button carries the click to InstantAdPay or LinkSpin, which report sign-ups
|
||||||
|
// and purchases against it. Also inside a redirect link of the member's own (go.example.com/go?u=https%3A%2F%2Finstantadpay.com...):
|
||||||
|
// only that one parameter is rewritten, every other one keeps its exact encoding. Spin and Banner Spin links are left alone, they
|
||||||
|
// make their own click. Only LinkSpin's own id shapes travel, never another network's clickid. Done on load, again when the page
|
||||||
|
// is ready and at the click, so a page script that rewrites its links first or later does not lose it.
|
||||||
|
var NET = /*ls-net*/["linkspin.app","instantadpay.com","instantadpay.link","ctbgo.com","mylinehq.com"]/*ls-net*/;
|
||||||
|
var OURS = /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/;
|
||||||
|
function netUrl(s) {
|
||||||
|
try { var u = new URL(s); return /^https?:$/.test(u.protocol) && NET.indexOf(u.hostname.toLowerCase().replace(/^www\./, '')) >= 0 && !/^\/(r|c|i)\//.test(u.pathname) ? u : null; } catch (e) { return null; }
|
||||||
|
}
|
||||||
|
function carries(u) { for (var i = 0; i < NAMES.length; i++) if (u.searchParams.has(NAMES[i])) return true; return false; }
|
||||||
|
function addId(s) { var h = s.indexOf('#'), b = h < 0 ? s : s.slice(0, h), t = h < 0 ? '' : s.slice(h); return b + (b.indexOf('?') < 0 ? '?' : /[?&]$/.test(b) ? '' : '&') + 'lsclk=' + encodeURIComponent(id) + t; }
|
||||||
|
function network(a) {
|
||||||
|
try {
|
||||||
|
if (!OURS.test(id) || a.getAttribute('data-ls-skip') != null) return false;
|
||||||
|
var href = a.href, n = netUrl(href);
|
||||||
|
if (n) { if (!carries(n)) a.href = addId(href); return true; }
|
||||||
|
var u = new URL(href); if (!/^https?:$/.test(u.protocol) || !u.search) return false;
|
||||||
|
var parts = u.search.slice(1).split('&'), found = false, changed = false;
|
||||||
|
for (var i = 0; i < parts.length; i++) {
|
||||||
|
var eq = parts[i].indexOf('='); if (eq < 1) continue;
|
||||||
|
var v; try { v = decodeURIComponent(parts[i].slice(eq + 1).replace(/\+/g, ' ')); } catch (e) { continue; }
|
||||||
|
var inner = /^https?:/i.test(v) ? netUrl(v) : null; if (!inner) continue;
|
||||||
|
found = true; if (carries(inner)) continue;
|
||||||
|
parts[i] = parts[i].slice(0, eq + 1) + encodeURIComponent(addId(v)); changed = true;
|
||||||
|
}
|
||||||
|
if (changed) a.href = href.slice(0, href.indexOf('?') + 1) + parts.join('&') + (u.hash || '');
|
||||||
|
return found;
|
||||||
|
} catch (e) { return false; }
|
||||||
|
}
|
||||||
|
function sweep() { try { var l = document.querySelectorAll('a[href]'); for (var i = 0; i < l.length; i++) network(l[i]); } catch (e) {} }
|
||||||
|
sweep();
|
||||||
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', sweep);
|
||||||
|
W.addEventListener('load', sweep);
|
||||||
|
function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a && !network(a)) decorate(a); } catch (er) {} }
|
||||||
document.addEventListener('click', onClick, true);
|
document.addEventListener('click', onClick, true);
|
||||||
document.addEventListener('auxclick', onClick, true);
|
document.addEventListener('auxclick', onClick, true);
|
||||||
} catch (e) { /* never break the member's page */ }
|
} catch (e) { /* never break the member's page */ }
|
||||||
|
|||||||
+2
-2
@@ -38,7 +38,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/team.js?v=20261020s"></script>
|
<script src="/assets/team.js?v=20261113org"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -64,7 +64,7 @@
|
|||||||
<div class="rules" id="rules"></div>
|
<div class="rules" id="rules"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
||||||
<script src="/assets/traffic-guide.js?v=20261029b"></script>
|
<script src="/assets/traffic-guide.js?v=20261029b"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+1
-1
@@ -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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/tx.js?v=20260906m"></script>
|
<script src="/assets/tx.js?v=20260906m"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+3
-1
@@ -21,6 +21,7 @@
|
|||||||
<div class="bio-head" id="bioHead" hidden>
|
<div class="bio-head" id="bioHead" hidden>
|
||||||
<img id="bioAvatar" class="bio-avatar" alt="" hidden>
|
<img id="bioAvatar" class="bio-avatar" alt="" hidden>
|
||||||
<img id="bioBadge" class="bio-badge" alt="achievement badge" hidden>
|
<img id="bioBadge" class="bio-badge" alt="achievement badge" hidden>
|
||||||
|
<img id="bioFounder" class="bio-badge" alt="Founder badge" hidden>
|
||||||
<div class="bio-meta">
|
<div class="bio-meta">
|
||||||
<p class="eyebrow">Your sponsor on LinkSpin</p>
|
<p class="eyebrow">Your sponsor on LinkSpin</p>
|
||||||
<h2 id="wallTitle" style="margin:.1em 0">Loading…</h2>
|
<h2 id="wallTitle" style="margin:.1em 0">Loading…</h2>
|
||||||
@@ -48,7 +49,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/wall.js?v=20261030pp"></script>
|
<script src="/assets/wall.js?v=20261030pp"></script>
|
||||||
|
<script src="/assets/wall-founder.js?v=20261105fd"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+6
-2
@@ -11,7 +11,11 @@
|
|||||||
<style>
|
<style>
|
||||||
.body{padding:16px 24px;display:grid;gap:16px}
|
.body{padding:16px 24px;display:grid;gap:16px}
|
||||||
.two{display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:16px}
|
.two{display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:16px}
|
||||||
.pay .hd,.pay .rw{grid-template-columns:110px minmax(0,1.4fr) 70px 110px 110px 120px}
|
.pay .hd,.pay .rw{grid-template-columns:110px minmax(120px,1.4fr) 70px 80px 110px 110px}
|
||||||
|
/* the payouts card shares its row with a 380px panel, so it is narrow on mid-size screens: switch to the stacked rows by the card's
|
||||||
|
own width, not the window's (Michael 2026-11-09: From and Level drew on top of each other) */
|
||||||
|
.pay{container-type:inline-size}
|
||||||
|
@container (max-width:700px){.pay .hd{display:none}.pay .rw{grid-template-columns:1fr 1fr}}
|
||||||
.pos .rw{grid-template-columns:minmax(0,1fr) 120px 100px}
|
.pos .rw{grid-template-columns:minmax(0,1fr) 120px 100px}
|
||||||
@media (max-width:900px){.two{grid-template-columns:1fr}.pay .hd{display:none}.pay .rw{grid-template-columns:1fr 1fr}.body{padding:12px 16px}}
|
@media (max-width:900px){.two{grid-template-columns:1fr}.pay .hd{display:none}.pay .rw{grid-template-columns:1fr 1fr}.body{padding:12px 16px}}
|
||||||
</style>
|
</style>
|
||||||
@@ -32,7 +36,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/wallet-screen.js?v=20261023ov"></script>
|
<script src="/assets/wallet-screen.js?v=20261023ov"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -120,7 +120,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=20261101t"></script>
|
<script src="/assets/common.js?v=20261113nl"></script>
|
||||||
<script src="/assets/wallets.js?v=20261026a"></script>
|
<script src="/assets/wallets.js?v=20261026a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -42,7 +42,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261101t"></script>
|
<script src="/assets/cr-shell.js?v=20261113nl"></script>
|
||||||
<script src="/assets/zones-screen.js?v=20261010a"></script>
|
<script src="/assets/zones-screen.js?v=20261010a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// BTC4Hits bridge + admin spin links (2026-11-11). Boots a throwaway LinkSpin (temp DATA_DIR, JSON stores, no mail key,
|
||||||
|
// ADMIN_PASSWORD=localtest) and checks:
|
||||||
|
// /from/btc4hits: 200, the sponsor cookie is cleared, angle b4h + forced first-touch source legacy:btc4hits, sign-in copy,
|
||||||
|
// no em dash in the copy; a sign-up through it gets NO welcome-back credits (legacy grant rule is fw/t1 only)
|
||||||
|
// /api/admin/rotations: POST with urls[] makes one spin link with every destination at weight 1, GET lists links + sources,
|
||||||
|
// DELETE removes it; auth required.
|
||||||
|
// node qa/btc4hits-bridge.test.mjs (B4H_PORT to move the port)
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const PORT = Number(process.env.B4H_PORT || 8831), BASE = 'http://127.0.0.1:' + PORT;
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
let pass = 0, fail = 0; const ok = (c, n, x) => { if (c) { pass++; console.log('ok ' + n); } else { fail++; console.log('FAIL ' + n + (x ? '\n ' + x : '')); } };
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'b4h-ls-')); fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true });
|
||||||
|
const now = Date.now();
|
||||||
|
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify({ v: 2, byEmail: { 'owner@qa.test': { email: 'owner@qa.test', pass: null, sponsorRef: '', code: 'cowner1', username: 'owner', address: null, created: now - 86400000, joinedVia: 'carried', joinedRef: 'network' } }, byAddress: {}, byCode: { cowner1: 'owner@qa.test' }, joins: 0, positions: {} }));
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', DATABASE_URL: '', SENDGRID_API_KEY: '', SENDGRID_KEY: '', OUTBOUND: '', LS_SYNC_SECRET: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' });
|
||||||
|
const log = path.join(dir, 'server.log');
|
||||||
|
const proc = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] });
|
||||||
|
const admin = (pth, method, body, auth = true) => fetch(BASE + pth, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, auth ? { Authorization: 'Bearer localtest' } : {}), body: body ? JSON.stringify(body) : undefined });
|
||||||
|
try {
|
||||||
|
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config', { signal: AbortSignal.timeout(2000) })).status < 500; } catch (e) { await sleep(1000); } }
|
||||||
|
ok(up, 'local LinkSpin up');
|
||||||
|
// 1. the bridge page
|
||||||
|
const r = await fetch(BASE + '/from/btc4hits?src=splash', { headers: { Cookie: 'iap.sponsor=someone' } });
|
||||||
|
const html = await r.text(); const ck = r.headers.getSetCookie ? r.headers.getSetCookie() : [];
|
||||||
|
ok(r.status === 200, '/from/btc4hits answers 200', String(r.status));
|
||||||
|
ok(ck.some(c => /^iap\.sponsor=;/.test(c) && /Max-Age=0/.test(c)), 'sponsor cookie cleared (no sponsor from the bridge itself)', ck.join(' | '));
|
||||||
|
ok(ck.some(c => /^iap\.angle=b4h;/.test(c)), 'angle b4h remembered');
|
||||||
|
ok(ck.some(c => c.startsWith('iap.ref=' + encodeURIComponent('legacy:btc4hits:splash') + ';')), 'forced first-touch source legacy:btc4hits', ck.join(' | '));
|
||||||
|
ok(/<title>BTC4Hits is now LinkSpin\. \| LinkSpin<\/title>/.test(html) && html.includes('class="squeeze"'), 'title + squeeze layout');
|
||||||
|
ok(html.includes('join.js?v=20261111b4h'), 'join.js version bumped');
|
||||||
|
const js = fs.readFileSync(path.join(SITE, 'public', 'assets', 'join.js'), 'utf8'); const b4h = (js.match(/\n\s+b4h: \{[^\n]+/) || [''])[0];
|
||||||
|
ok(b4h.includes('Sign in with your BTC4Hits email') && b4h.includes("cta: 'Sign in with your email'"), 'sign-in call to action in the b4h copy');
|
||||||
|
ok(!/—/.test(b4h) && !/—/.test(html.match(/<title>[^<]*/)[0]), 'no em dash in the copy');
|
||||||
|
// a brand-new sign-up arriving through the bridge: no welcome-back credits
|
||||||
|
const st = await (await fetch(BASE + '/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: 'iap.angle=b4h; iap.ref=legacy%3Abtc4hits' }, body: JSON.stringify({ email: 'newb4h@qa.test', fts: Date.now() - 8000 }) })).json();
|
||||||
|
if (st.devCode) {
|
||||||
|
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: 'iap.angle=b4h; iap.ref=legacy%3Abtc4hits' }, body: JSON.stringify({ email: 'newb4h@qa.test', code: st.devCode }) });
|
||||||
|
ok(v.status === 200, 'sign-up through the bridge works', String(v.status));
|
||||||
|
await sleep(300);
|
||||||
|
ok(!fs.existsSync(path.join(dir, 'legacy-grants.json')) && !/legacy grant/.test(fs.readFileSync(log, 'utf8')), 'no welcome-back credits granted');
|
||||||
|
const a = JSON.parse(fs.readFileSync(path.join(dir, 'accounts.json'), 'utf8')).byEmail['newb4h@qa.test'];
|
||||||
|
ok(a && a.joinedVia === 'b4h' && a.joinedRef === 'legacy:btc4hits', 'account records angle b4h + source legacy:btc4hits', JSON.stringify(a && { v: a.joinedVia, r: a.joinedRef }));
|
||||||
|
// 1b. Holding tank menu item (2026-11-11): the summary route, and the rail item in a real browser
|
||||||
|
const cookies = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]);
|
||||||
|
const sum = await (await fetch(BASE + '/api/my/tank/summary', { headers: { Cookie: cookies.join('; ') } })).json();
|
||||||
|
ok(sum.adopter === false && sum.cap === 10 && typeof sum.waiting === 'number', '/api/my/tank/summary: a new member is not an adopter, cap 10 from the setting', JSON.stringify(sum));
|
||||||
|
ok((await fetch(BASE + '/api/my/tank/summary')).status === 401, '/api/my/tank/summary needs a sign-in');
|
||||||
|
try {
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const browser = await chromium.launch();
|
||||||
|
const shot = async (summary) => {
|
||||||
|
const ctx = await browser.newContext(); await ctx.addCookies(cookies.map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
||||||
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
||||||
|
if (summary) await page.route('**/api/my/tank/summary', r => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(summary) }));
|
||||||
|
await page.goto(BASE + '/links', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
|
||||||
|
const out = await page.evaluate(() => { const a = document.getElementById('crTank'); return a ? { hidden: a.hidden, href: a.getAttribute('href'), title: a.title, badge: (a.querySelector('.rbadge') || {}).textContent || '', label: (a.querySelector('.lbl') || {}).textContent || '' } : null; });
|
||||||
|
await ctx.close(); return Object.assign({ errs }, out || {});
|
||||||
|
};
|
||||||
|
const s1 = await shot(null);
|
||||||
|
ok(s1.href === '/tools#line' && s1.hidden === true, 'rail: Holding tank item hidden for a member who cannot adopt', JSON.stringify(s1));
|
||||||
|
const s2 = await shot({ adopter: true, eligible: true, full: false, held: 2, cap: 10, waiting: 1234 });
|
||||||
|
ok(s2.hidden === false && s2.label === 'Holding tank' && s2.badge === '999+', 'rail: shown for an adopter, with the waiting badge', JSON.stringify(s2));
|
||||||
|
ok(/You can adopt up to 10 people at a time\./.test(s2.title) && /1,234 waiting/.test(s2.title) && !/\u2014/.test(s2.title), 'rail: one line with the cap from the setting', s2.title);
|
||||||
|
const s3 = await shot({ adopter: true, eligible: false, full: true, held: 7, cap: 7, waiting: 0 });
|
||||||
|
ok(s3.hidden === false && !s3.badge && /up to 7 people at a time/.test(s3.title), 'rail: an adopter at the cap still sees it; cap read from the response (7), no badge when nobody waits', JSON.stringify(s3));
|
||||||
|
ok(!s1.errs.length && !s2.errs.length, 'no page errors', JSON.stringify(s1.errs.concat(s2.errs)).slice(0, 200));
|
||||||
|
await browser.close();
|
||||||
|
} catch (e) { ok(false, 'browser check ran', e.message); }
|
||||||
|
} else ok(false, 'dev sign-in code available', JSON.stringify(st));
|
||||||
|
// 2. admin spin links
|
||||||
|
ok((await admin('/api/admin/rotations?email=owner@qa.test', 'GET', null, false)).status === 401, 'GET needs admin');
|
||||||
|
const urls = ['https://example.com/a', 'https://example.org/b', 'example.net/c'].map(u => ({ url: u, label: 'x' }));
|
||||||
|
const p = await (await admin('/api/admin/rotations', 'POST', { email: 'owner@qa.test', source: { name: 'BTC4Hits', site: 'btc4hits.com' }, links: [{ name: 'BTC4Hits rotator #7', url: urls[0].url, fallback: urls[0].url, urls }] })).json();
|
||||||
|
ok(p.ok && p.links[0].dests === 3 && p.links[0].code, 'POST makes one link with 3 destinations', JSON.stringify(p));
|
||||||
|
const g = await (await admin('/api/admin/rotations?email=owner@qa.test', 'GET')).json();
|
||||||
|
const rot = (g.rotations || []).find(x => x.name === 'BTC4Hits rotator #7');
|
||||||
|
ok(rot && rot.destinations.length === 3 && rot.destinations.every(d => d.weight === 1 && d.active) && rot.destinations[2].url === 'https://example.net/c', 'GET lists it: 3 active destinations, weight 1, cleaned URLs');
|
||||||
|
ok(rot && rot.sourceId && (g.sources || []).some(s => s.id === rot.sourceId && s.name === 'BTC4Hits'), 'attached to the BTC4Hits source');
|
||||||
|
ok(typeof g.linkBase === 'string' && g.linkBase.endsWith('/r/'), 'linkBase given');
|
||||||
|
const red = await fetch(BASE + '/r/' + rot.code, { redirect: 'manual', headers: { 'User-Agent': 'curl/8' } });
|
||||||
|
ok(red.status >= 301 && red.status <= 308 && urls.some(u => red.headers.get('location').startsWith(u.url.startsWith('http') ? u.url : 'https://' + u.url)), '/r/<code> redirects to one of them', red.status + ' ' + red.headers.get('location'));
|
||||||
|
const d = await admin('/api/admin/rotations?email=owner@qa.test&id=' + rot.id, 'DELETE');
|
||||||
|
ok(d.status === 200, 'DELETE removes it');
|
||||||
|
const g2 = await (await admin('/api/admin/rotations?email=owner@qa.test', 'GET')).json();
|
||||||
|
ok(!(g2.rotations || []).length, 'gone after DELETE');
|
||||||
|
ok((await admin('/api/admin/rotations?email=nobody@qa.test', 'GET')).status === 404, 'unknown member -> 404');
|
||||||
|
} finally { proc.kill(); }
|
||||||
|
console.log('\n' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// hubsync.js against a real network hub (2026-11-12): the hub runs in this process in JSON mode on a temp DATA_DIR and posts
|
||||||
|
// its events to a local copy of LinkSpin's /api/hub/events route; LinkSpin's accounts + registry are the JSON stores in
|
||||||
|
// another temp folder. Synthetic people only. HUB_DIR=<network-hub checkout> node qa/hubsync.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const assert = require('assert');
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const http = require('http');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const HUB_DIR = process.env.HUB_DIR || [path.join(__dirname, '..', '..', 'network-hub'), path.join(__dirname, '..', '..', '..', 'network-hub')].find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const LS_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-hub-')); const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-data-'));
|
||||||
|
const LS_SECRET = 'l'.repeat(40), CTB_SECRET = 'c'.repeat(40);
|
||||||
|
delete process.env.DATABASE_URL; delete process.env.HUB_ENABLED;
|
||||||
|
const accounts = require(path.join(__dirname, '..', 'accounts.js'));
|
||||||
|
const registry = require(path.join(__dirname, '..', 'registry.js'));
|
||||||
|
const carry = require(path.join(__dirname, '..', 'carry.js'));
|
||||||
|
const hubsync = require(path.join(__dirname, '..', 'hubsync.js'));
|
||||||
|
accounts.init({ dataDir: LS_DIR }); registry.init({ dataDir: LS_DIR });
|
||||||
|
hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null });
|
||||||
|
accounts.onChange(e => hubsync.touch(e));
|
||||||
|
const E = n => n + '@example.test';
|
||||||
|
const W = n => '0x' + String(n).padStart(40, '0');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
// LinkSpin's route, exactly as server.js wires it
|
||||||
|
const ls = http.createServer((req, res) => {
|
||||||
|
let d = ''; req.on('data', c => { d += c; }); req.on('end', async () => {
|
||||||
|
if (req.url !== '/api/hub/events' || !hubsync.on()) { res.writeHead(404); return res.end('{}'); }
|
||||||
|
const r = await hubsync.receive(req.headers, d); res.writeHead(r.status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(r.body));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise(r => ls.listen(0, r)); const lsPort = ls.address().port;
|
||||||
|
|
||||||
|
// 1. flag off: nothing is queued, the route answers 404, no state file is written
|
||||||
|
hubsync.touch(E('nobody'));
|
||||||
|
assert.strictEqual(hubsync.on(), false);
|
||||||
|
assert.strictEqual((await hubsync.receive({}, '{"events":[]}')).status, 404);
|
||||||
|
assert.strictEqual(hubsync.adminView().outbox, 0, 'nothing queued while off');
|
||||||
|
assert.ok(!fs.existsSync(path.join(LS_DIR, 'hubsync.json')), 'no state written while off');
|
||||||
|
|
||||||
|
// the hub, JSON mode, with LinkSpin's hook pointed at the local route
|
||||||
|
process.env.DATA_DIR = HUB_DATA; process.env.HUB_ADMIN_SECRET = 'a'.repeat(40);
|
||||||
|
process.env.HUB_SITES = JSON.stringify({ linkspin: { secret: LS_SECRET, hook: `http://127.0.0.1:${lsPort}/api/hub/events`, seeEmails: true }, ctb: { secret: CTB_SECRET, seeEmails: true } });
|
||||||
|
const { start } = require(path.join(HUB_DIR, 'server.js'));
|
||||||
|
const hooks = require(path.join(HUB_DIR, 'lib', 'hooks.js')); const hstore = require(path.join(HUB_DIR, 'lib', 'store.js')); const { sign } = require(path.join(HUB_DIR, 'lib', 'signing.js'));
|
||||||
|
const hub = await start(0); const hubPort = hub.address().port;
|
||||||
|
const ctb = async (route, body) => { const raw = JSON.stringify(body); const ts = String(Date.now()); const r = await fetch(`http://127.0.0.1:${hubPort}${route}`, { method: 'POST', body: raw, headers: { 'X-Hub-Site': 'ctb', 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(CTB_SECRET, ts, raw) } }); return r.json(); };
|
||||||
|
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; process.env.HUB_SECRET = LS_SECRET;
|
||||||
|
assert.strictEqual(hubsync.on(), true);
|
||||||
|
const lastSeq = () => hstore.eventsAfter(0, 1e6).slice(-1)[0].seq;
|
||||||
|
try {
|
||||||
|
// 2. signature: a bad signature and a stale timestamp are refused
|
||||||
|
const raw = '{"events":[]}'; const ts = String(Date.now());
|
||||||
|
const hmac = (t, b) => crypto.createHmac('sha256', LS_SECRET).update(t + '\n' + b).digest('hex');
|
||||||
|
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': hmac(ts, raw + ' ') }, raw)).status, 401, 'bad signature');
|
||||||
|
const old = String(Date.now() - 6 * 60000);
|
||||||
|
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': old, 'x-hub-sig': hmac(old, raw) }, raw)).status, 401, 'older than 5 minutes');
|
||||||
|
assert.strictEqual((await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': hmac(ts, raw) }, raw)).status, 200);
|
||||||
|
|
||||||
|
// 3. CTB joins become waiting LinkSpin accounts under the hub sponsor
|
||||||
|
await ctb('/v1/join', { email: E('ann'), username: 'ann' });
|
||||||
|
await ctb('/v1/join', { email: E('bob'), username: 'bobby', ref: 'ann' });
|
||||||
|
await hooks.tick();
|
||||||
|
const ann = await accounts.byEmail(E('ann')), bob = await accounts.byEmail(E('bob'));
|
||||||
|
assert.ok(ann && bob, 'shells created');
|
||||||
|
assert.strictEqual(bob.joinedVia, 'carried'); assert.strictEqual(bob.joinedRef, 'network');
|
||||||
|
assert.strictEqual(bob.username, 'bobby'); assert.strictEqual((await accounts.sponsorOf(E('bob'))).email, E('ann'));
|
||||||
|
assert.strictEqual((await registry.get(E('bob'))).firstProperty, 'ctb');
|
||||||
|
assert.strictEqual(hubsync.adminView().stats.shells, 2);
|
||||||
|
|
||||||
|
// 4. the same events delivered twice change nothing
|
||||||
|
const before = JSON.stringify(await accounts.listAll(100)); const evs = hubsync.adminView().stats.events;
|
||||||
|
hstore.setCursor('linkspin', 0); await hstore.flush(); await hooks.tick();
|
||||||
|
assert.strictEqual(JSON.stringify(await accounts.listAll(100)), before, 'duplicate delivery is a no-op');
|
||||||
|
assert.strictEqual(hubsync.adminView().stats.events, evs, 'seqs already applied are skipped');
|
||||||
|
|
||||||
|
// 5. a sponsor new to LinkSpin is placed first, from the hub, even when only the member's event arrives
|
||||||
|
await ctb('/v1/join', { email: E('dave'), username: 'dave' }); const daveSeq = lastSeq();
|
||||||
|
await ctb('/v1/join', { email: E('erin'), username: 'erin', ref: 'dave' });
|
||||||
|
hstore.setCursor('linkspin', daveSeq); await hstore.flush(); await hooks.tick();
|
||||||
|
assert.ok(await accounts.byEmail(E('dave')), 'sponsor placed first');
|
||||||
|
assert.strictEqual((await accounts.sponsorOf(E('erin'))).email, E('dave'));
|
||||||
|
|
||||||
|
// 6. wallet.connected fills an empty wallet
|
||||||
|
await ctb('/v1/wallet', { email: E('bob'), wallet: W(7) }); await hooks.tick();
|
||||||
|
assert.strictEqual((await accounts.byEmail(E('bob'))).address, W(7));
|
||||||
|
|
||||||
|
// 7. LinkSpin's own sign-up and wallet reach the hub, sponsor named by email
|
||||||
|
await accounts.ensure(E('zed'), 'ann', '', null); await accounts.setUsername(E('zed'), 'zed');
|
||||||
|
await hubsync.flush();
|
||||||
|
let hz = await ctb('/v1/resolve', { email: E('zed') });
|
||||||
|
assert.strictEqual(hz.person.sponsor.email, E('ann')); assert.strictEqual(hz.person.firstDoor.site, 'linkspin'); assert.strictEqual(hz.person.username, 'zed');
|
||||||
|
await accounts.linkWallet(E('zed'), W(9)); await hubsync.flush();
|
||||||
|
hz = await ctb('/v1/resolve', { email: E('zed') }); assert.strictEqual(hz.person.wallet, W(9));
|
||||||
|
const zedBefore = JSON.stringify(await accounts.byEmail(E('zed')));
|
||||||
|
await hooks.tick(); // our own join and wallet come back from the hub: nothing changes here
|
||||||
|
assert.strictEqual(JSON.stringify(await accounts.byEmail(E('zed'))), zedBefore);
|
||||||
|
assert.strictEqual(hubsync.adminView().stats.shells, 4, 'no shell made for our own member');
|
||||||
|
|
||||||
|
// 8. hub and LinkSpin disagree: the earlier CTB join under ann is the hub's answer, LinkSpin's own line stands, it is logged
|
||||||
|
await ctb('/v1/join', { email: E('pat'), ref: 'ann' });
|
||||||
|
await accounts.ensure(E('pat'), 'zed', '', null); await hubsync.flush();
|
||||||
|
assert.strictEqual((await accounts.sponsorOf(E('pat'))).email, E('zed'), 'LinkSpin line not moved');
|
||||||
|
assert.strictEqual((await ctb('/v1/resolve', { email: E('pat') })).person.sponsor.email, E('ann'), 'hub keeps the earliest join');
|
||||||
|
const dv = hubsync.adminView(); assert.strictEqual(dv.disagreeTotal, 1); assert.ok(!JSON.stringify(dv.disagree).includes(E('pat')), 'admin view masks emails');
|
||||||
|
await hooks.tick(); assert.strictEqual((await accounts.sponsorOf(E('pat'))).email, E('zed'));
|
||||||
|
|
||||||
|
// 9. hub down: the join waits in the persisted outbox and goes once the hub is back
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:1';
|
||||||
|
await accounts.ensure(E('quinn'), 'ann', '', null); await hubsync.flush();
|
||||||
|
assert.strictEqual(hubsync.adminView().outbox, 1, 'kept for retry');
|
||||||
|
assert.ok(JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')).outbox[E('quinn')], 'outbox persisted');
|
||||||
|
process.env.HUB_URL = `http://127.0.0.1:${hubPort}`;
|
||||||
|
const st = JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')); st.outbox[E('quinn')].next = 0; fs.writeFileSync(path.join(LS_DIR, 'hubsync.json'), JSON.stringify(st));
|
||||||
|
hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null }); // reload from disk, as after a restart
|
||||||
|
await hubsync.flush();
|
||||||
|
assert.strictEqual(hubsync.adminView().outbox, 0);
|
||||||
|
assert.strictEqual((await ctb('/v1/resolve', { email: E('quinn') })).person.firstDoor.site, 'linkspin');
|
||||||
|
|
||||||
|
// 10. hub unreachable while LinkSpin is receiving: 503 so the hub sends again, nothing skipped
|
||||||
|
await hooks.tick(); await ctb('/v1/join', { email: E('rose') });
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:1'; const seqNow = hubsync.adminView().lastSeq;
|
||||||
|
await hooks.tick(); assert.strictEqual(hubsync.adminView().lastSeq, seqNow, 'not advanced while the hub cannot be asked');
|
||||||
|
process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; await hooks.tick();
|
||||||
|
assert.ok(await accounts.byEmail(E('rose')), 'arrived on the retry');
|
||||||
|
console.log('hubsync: ok (10 checks)');
|
||||||
|
} finally { hub.close(); ls.close(); }
|
||||||
|
process.exit(0);
|
||||||
|
})().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); });
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
// Launch week tests (2026-11-05): contest window in Central time, exclusions, minimum sales, payout idempotency (two app
|
||||||
|
// copies), Founder criterion + grant, touchSeen firstSeen backfill. Throwaway DATA_DIR, FAKE chain, FAKE signer: nothing
|
||||||
|
// here touches Polygon, the production volume or a real member. Run: node qa/launchweek.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const LW = require(path.join(ROOT, 'launchweek.js'));
|
||||||
|
const E = 10n ** 18n;
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
async function test(name, fn) { try { await fn(); pass++; console.log(' ok ' + name); } catch (e) { fail++; console.log(' FAIL ' + name + '\n ' + (e && e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); } }
|
||||||
|
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'lwtest-'));
|
||||||
|
const tickAsync = () => new Promise(r => setImmediate(r));
|
||||||
|
const T = iso => Date.parse(iso);
|
||||||
|
const LAUNCH = T('2026-11-15T06:00:00-06:00'), END = T('2026-11-22T00:00:00-06:00');
|
||||||
|
|
||||||
|
// ---- fakes ----
|
||||||
|
function fakeAccounts(list, positions) {
|
||||||
|
const by = {}; for (const a of list) by[a.email] = Object.assign({ memberId: 0, created: 1 }, a);
|
||||||
|
return { by,
|
||||||
|
listAll: async () => Object.values(by).map(a => Object.assign({}, a)),
|
||||||
|
positions: async e => (positions[e] || []).map(id => ({ memberId: id })),
|
||||||
|
byEmail: async e => by[e] ? Object.assign({}, by[e]) : null,
|
||||||
|
setFounder: async (e, ts) => { await tickAsync(); const a = by[e]; if (!a) return { error: 'no' }; if (a.founder) return { ok: true, already: true }; a.founder = ts; return { ok: true }; } };
|
||||||
|
}
|
||||||
|
// sales: [sponsorId (TierPaid recipient), buyerId, ts, cents]
|
||||||
|
function fakeChain(sales, extra) {
|
||||||
|
const ev = []; sales.forEach(([rec, buyer, ts, cents], i) => {
|
||||||
|
ev.push({ type: 'Purchase', tx: '0xp' + i, buyerId: buyer, priceCents: cents || 2500, ts });
|
||||||
|
ev.push({ type: 'TierPaid', tx: '0xp' + i, tier: 1, recipientId: rec, buyerId: buyer, amountWei: '1', ts });
|
||||||
|
});
|
||||||
|
return { events: ev.concat(extra || []), recentEvents() { return this.events; } };
|
||||||
|
}
|
||||||
|
function sharedMarks() { const set = new Set(); return { set, claim: async k => { await tickAsync(); if (set.has(k)) return false; set.add(k); return true; } }; }
|
||||||
|
function fakePayer(balanceWei, opts) {
|
||||||
|
const o = opts || {}; let n = 0;
|
||||||
|
const p = { address: '0x00000000000000000000000000000000000000aa', bal: BigInt(balanceWei), sends: [],
|
||||||
|
balance: async () => { await tickAsync(); return p.bal; },
|
||||||
|
fees: async () => ({ maxFeePerGas: 100n * 10n ** 9n, maxPriorityFeePerGas: 30n * 10n ** 9n }),
|
||||||
|
preflight: async id => { await tickAsync(); if ((o.reject || []).includes(id)) throw Object.assign(new Error('execution reverted'), { reason: 'Send failed' }); },
|
||||||
|
send: async (id, wei) => { await tickAsync(); await tickAsync(); p.sends.push({ id, wei: BigInt(wei) }); p.bal -= BigInt(wei); const hash = '0x' + (++n).toString(16).padStart(64, '0'); return { hash, wait: async () => { await tickAsync(); return { status: 1 }; } }; } };
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
function freshLeaderboard(accounts) {
|
||||||
|
delete require.cache[require.resolve(path.join(ROOT, 'leaderboard.js'))];
|
||||||
|
const lb = require(path.join(ROOT, 'leaderboard.js'));
|
||||||
|
lb.init({ accounts, chain: { recentEvents: () => [] }, ads: {}, dataDir: tmp(), siteConfig: () => ({}), adminEmail: 'admin@x.test' });
|
||||||
|
return lb;
|
||||||
|
}
|
||||||
|
function instance(o) {
|
||||||
|
const lw = LW.create();
|
||||||
|
lw.init({ accounts: o.accounts, chain: o.chain, marks: o.marks || sharedMarks(), leaderboard: o.lb || freshLeaderboard(o.accounts), siteConfig: () => o.site || {}, dataDir: o.dir || tmp(), adminEmail: 'admin@x.test', payer: () => o.payer || null, txLink: h => 'https://polygonscan.example/tx/' + h, now: () => o.clock.t });
|
||||||
|
return lw;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a world: admin #1 (house), alice #10 (+ linked position #11), bob #20, carol #30, dave #40, buyers #100+
|
||||||
|
const ACCTS = [
|
||||||
|
{ email: 'admin@x.test', memberId: 1, username: 'martbost' },
|
||||||
|
{ email: 'alice@x.test', memberId: 10, username: 'alice' },
|
||||||
|
{ email: 'bob@x.test', memberId: 20, username: 'bob' },
|
||||||
|
{ email: 'carol@x.test', memberId: 30, username: 'carol' },
|
||||||
|
{ email: 'dave@x.test', memberId: 40, username: 'dave' },
|
||||||
|
{ email: 'erin@x.test', memberId: 50, username: 'erin' },
|
||||||
|
...[100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110].map(id => ({ email: 'b' + id + '@x.test', memberId: id }))
|
||||||
|
];
|
||||||
|
const POS = { 'alice@x.test': [11], 'carol@x.test': [31] };
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
console.log('launchweek.test: window (Central time)');
|
||||||
|
await test('defaults: launch Sun 2026-11-15 06:00 CST = 12:00 UTC; window ends at Sun 2026-11-22 00:00 CST (exclusive)', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain([]), clock: { t: LAUNCH } });
|
||||||
|
const c = lw.cfg();
|
||||||
|
assert.strictEqual(new Date(c.launchAt).toISOString(), '2026-11-15T12:00:00.000Z');
|
||||||
|
assert.strictEqual(c.start, c.launchAt);
|
||||||
|
assert.strictEqual(new Date(c.end).toISOString(), '2026-11-22T06:00:00.000Z');
|
||||||
|
assert.deepStrictEqual(c.prizes, ['10', '6', '4']); assert.strictEqual(c.minSales, 2);
|
||||||
|
});
|
||||||
|
await test('bounds: 05:59:59.999 CT Sunday out, 06:00 in, Sat 23:59:59 CT in, Sun 00:00 CT out', async () => {
|
||||||
|
const sales = [[20, 100, LAUNCH - 1], [20, 101, LAUNCH], [20, 102, T('2026-11-21T23:59:59-06:00')], [20, 103, END]];
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(sales), clock: { t: END + 3600000 } });
|
||||||
|
const s = await lw.standings();
|
||||||
|
assert.strictEqual(s.rows.length, 1); assert.strictEqual(s.rows[0].email, 'bob@x.test'); assert.strictEqual(s.rows[0].sales, 2);
|
||||||
|
assert.strictEqual(s.open, false);
|
||||||
|
});
|
||||||
|
await test('settings move the window without a deploy (launchAt and launchContestEnd)', async () => {
|
||||||
|
const site = { launchAt: '2026-11-16T09:00:00-06:00', launchContestEnd: '2026-11-17T00:00:00-06:00' };
|
||||||
|
const sales = [[20, 100, T('2026-11-16T08:59:00-06:00')], [20, 101, T('2026-11-16T09:00:00-06:00')], [20, 102, T('2026-11-16T23:00:00-06:00')], [20, 103, T('2026-11-17T00:00:00-06:00')]];
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(sales), site, clock: { t: T('2026-11-18T00:00:00Z') } });
|
||||||
|
const s = await lw.standings(); assert.strictEqual(s.rows[0].sales, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('launchweek.test: exclusions + minimum');
|
||||||
|
const D = h => LAUNCH + h * 3600000;
|
||||||
|
const WORLD = [
|
||||||
|
[10, 100, D(1)], [10, 101, D(2)], [10, 102, D(3)], // alice: 3 real sales
|
||||||
|
[10, 11, D(4)], // alice's own linked position bought under her: own, never counts
|
||||||
|
[20, 31, D(5)], // bob sold to carol's linked position: linked positions never count
|
||||||
|
[20, 103, D(6)], [20, 104, D(7)], // bob: 2 real sales
|
||||||
|
[1, 105, D(8)], [1, 106, D(9)], [1, 107, D(10)], // admin/company #1: never a contestant
|
||||||
|
[30, 1, D(11)], [30, 108, D(12)], // carol: one sale is a company placement (buyer = admin #1), one real
|
||||||
|
[40, 109, D(13)], [40, 110, D(14)], // dave: 2 real sales (excluded by setting in one test)
|
||||||
|
[50, 100, D(2)] // erin: one sale (under the minimum)
|
||||||
|
];
|
||||||
|
await test('own positions, linked positions, admin and house sponsors, company buys never count', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
|
||||||
|
const s = await lw.standings(); const by = Object.fromEntries(s.rows.map(r => [r.email, r]));
|
||||||
|
assert.strictEqual(by['alice@x.test'].sales, 3);
|
||||||
|
assert.strictEqual(by['bob@x.test'].sales, 2);
|
||||||
|
assert.strictEqual(by['carol@x.test'].sales, 1);
|
||||||
|
assert.ok(!by['admin@x.test']);
|
||||||
|
});
|
||||||
|
await test('minimum 2 to place; ties broken by dollars then who got there first; prizes 10/6/4', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
|
||||||
|
const s = await lw.standings();
|
||||||
|
assert.deepStrictEqual(s.winners.map(w => [w.place, w.email, w.pol, w.memberId]), [[1, 'alice@x.test', '10', 10], [2, 'bob@x.test', '6', 20], [3, 'dave@x.test', '4', 40]]);
|
||||||
|
assert.ok(s.rows.find(r => r.email === 'erin@x.test' && !r.qualifies));
|
||||||
|
});
|
||||||
|
await test('launchContestExcludeEmails / ExcludeIds and a higher minimum', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), site: { launchContestExcludeEmails: 'dave@x.test', launchContestMinSales: 3 }, clock: { t: END + 1 } });
|
||||||
|
const s = await lw.standings();
|
||||||
|
assert.deepStrictEqual(s.winners.map(w => w.email), ['alice@x.test']);
|
||||||
|
const lw2 = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), site: { launchContestExcludeIds: '10' }, clock: { t: END + 1 } });
|
||||||
|
assert.ok(!(await lw2.standings()).rows.find(r => r.email === 'alice@x.test'));
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('launchweek.test: payout (fake signer)');
|
||||||
|
const expectOf = async lw => (await lw.standings(END)).winners.map(w => ({ place: w.place, memberId: w.memberId, pol: w.pol }));
|
||||||
|
await test('refused while the window is open; refused without a payer', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer: fakePayer(100n * E), clock: { t: END - 1 } });
|
||||||
|
assert.ok((await lw.pay([])).error.includes('still open'));
|
||||||
|
const lw2 = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock: { t: END + 1 } });
|
||||||
|
assert.ok((await lw2.pay([])).error.includes('payer'));
|
||||||
|
});
|
||||||
|
await test('a list that differs from the frozen result is refused, nothing sent', async () => {
|
||||||
|
const payer = fakePayer(100n * E);
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer, clock: { t: END + 1 } });
|
||||||
|
const ex = await expectOf(lw); ex[0].pol = '20';
|
||||||
|
const r = await lw.pay(ex); assert.ok(r.error && r.error.includes('does not match')); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
});
|
||||||
|
await test('not enough POL in the payer: refused before any send', async () => {
|
||||||
|
const payer = fakePayer(19n * E);
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), payer, clock: { t: END + 1 } });
|
||||||
|
const r = await lw.pay(await expectOf(lw)); assert.ok(r.error && r.error.includes('Nothing was sent')); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
});
|
||||||
|
await test('two app copies press Pay at once: each place paid exactly once; a third press pays nothing', async () => {
|
||||||
|
const dir = tmp(), marks = sharedMarks(), payer = fakePayer(100n * E), clock = { t: END + 3600000 };
|
||||||
|
const accounts = fakeAccounts(ACCTS, POS), chain = fakeChain(WORLD);
|
||||||
|
const a = instance({ accounts, chain, payer, marks, dir, clock }), b = instance({ accounts, chain, payer, marks, dir, clock });
|
||||||
|
const ex = await expectOf(a);
|
||||||
|
const [ra, rb] = await Promise.all([a.pay(ex), b.pay(ex)]);
|
||||||
|
assert.ok(!ra.error && !rb.error, JSON.stringify([ra.error, rb.error]));
|
||||||
|
assert.deepStrictEqual(payer.sends.map(s => [s.id, s.wei]).sort((x, y) => x[0] - y[0]), [[10, 10n * E], [20, 6n * E], [40, 4n * E]]);
|
||||||
|
const r3 = await a.pay(ex); assert.strictEqual(r3.paidNow, 0); assert.strictEqual(payer.sends.length, 3);
|
||||||
|
const v = await a.adminView(); assert.ok(v.payouts.every(x => x.state === 'paid' && /^0x/.test(x.txHash)));
|
||||||
|
assert.strictEqual(await a.panelHtml(), ''); // panel gone after the payout
|
||||||
|
assert.ok(a.txInfo(v.payouts[0].txHash));
|
||||||
|
});
|
||||||
|
await test('frozen result does not move when late sales index after the first press', async () => {
|
||||||
|
const dir = tmp(), payer = fakePayer(100n * E, { reject: [40] }), clock = { t: END + 1 }, chain = fakeChain(WORLD), accounts = fakeAccounts(ACCTS, POS);
|
||||||
|
const lw = instance({ accounts, chain, payer, dir, clock });
|
||||||
|
const ex = await expectOf(lw); const r = await lw.pay(ex);
|
||||||
|
assert.strictEqual(r.paidNow, 2); assert.strictEqual(r.payouts.find(x => x.place === 3).state, 'blocked');
|
||||||
|
chain.events.push({ type: 'TierPaid', tier: 1, recipientId: 50, buyerId: 101, ts: D(20), tx: '0xlate' }, { type: 'TierPaid', tier: 1, recipientId: 50, buyerId: 102, ts: D(21), tx: '0xlate2' });
|
||||||
|
const v = await lw.adminView(); assert.deepStrictEqual(v.wouldPay.map(w => w.email), ['alice@x.test', 'bob@x.test', 'dave@x.test']);
|
||||||
|
// the blocked place: admin checked, releases it once; the next press pays it, and only it
|
||||||
|
payer.sends.length = 0; const rr = await lw.resolve(3, 'retry'); assert.ok(rr.ok);
|
||||||
|
// still rejected by the wallet: stays blocked, nothing sent
|
||||||
|
await lw.pay(ex); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
assert.ok((await lw.resolve(1, 'retry')).error); // a paid place can never be released
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('launchweek.test: Founder');
|
||||||
|
const FA = [
|
||||||
|
{ email: 'early@x.test', lastSeen: LAUNCH - 86400000 }, // signed in before, never since
|
||||||
|
{ email: 'both@x.test', firstSeen: LAUNCH - 3 * 86400000, lastSeen: LAUNCH + 3600000 }, // before and after
|
||||||
|
{ email: 'late@x.test', firstSeen: LAUNCH + 60000, lastSeen: LAUNCH + 3600000 }, // first visit after launch
|
||||||
|
{ email: 'edge@x.test', firstSeen: LAUNCH, lastSeen: LAUNCH }, // exactly at the launch moment: not before
|
||||||
|
{ email: 'shell@x.test', joinedVia: 'carried' }, // carried over, never signed in
|
||||||
|
{ email: 'oldlast@x.test', lastSeen: LAUNCH + 5000 } // no firstSeen, only a post-launch lastSeen
|
||||||
|
];
|
||||||
|
await test('criterion: earliest signed-in visit strictly before the launch moment', async () => {
|
||||||
|
const lw = instance({ accounts: fakeAccounts(FA, {}), chain: fakeChain([]), clock: { t: LAUNCH - 1000 } });
|
||||||
|
const q = FA.filter(a => lw.qualifiesFounder(a, LAUNCH)).map(a => a.email);
|
||||||
|
assert.deepStrictEqual(q, ['early@x.test', 'both@x.test']);
|
||||||
|
const p = await lw.founderPreview(); assert.strictEqual(p.qualify, 2); assert.strictEqual(p.neverSignedIn, 1); assert.strictEqual(p.launched, false);
|
||||||
|
});
|
||||||
|
await test('grant refused before launch; automatic tick grants from launch; idempotent; two copies grant once each account', async () => {
|
||||||
|
const accounts = fakeAccounts(FA, {}), clock = { t: LAUNCH - 1000 }, marks = sharedMarks();
|
||||||
|
const a = instance({ accounts, chain: fakeChain([]), clock, marks }), b = instance({ accounts, chain: fakeChain([]), clock, marks });
|
||||||
|
assert.ok((await a.grantFounders()).error); await a.tick();
|
||||||
|
assert.ok(!Object.values(accounts.by).some(x => x.founder));
|
||||||
|
clock.t = LAUNCH + 60000;
|
||||||
|
await Promise.all([a.tick(), b.tick()]);
|
||||||
|
assert.deepStrictEqual(Object.values(accounts.by).filter(x => x.founder).map(x => x.email).sort(), ['both@x.test', 'early@x.test']);
|
||||||
|
assert.ok(Object.values(accounts.by).filter(x => x.founder).every(x => x.founder === LAUNCH));
|
||||||
|
clock.t += 600000; const r = await a.grantFounders(); assert.strictEqual(r.granted, 0);
|
||||||
|
assert.strictEqual(a.founderState(accounts.by['early@x.test']).founder, true);
|
||||||
|
assert.strictEqual(a.founderState(accounts.by['late@x.test']).founder, false);
|
||||||
|
});
|
||||||
|
await test('founderGrant 0 switches the automatic grant off', async () => {
|
||||||
|
const accounts = fakeAccounts(FA, {});
|
||||||
|
const lw = instance({ accounts, chain: fakeChain([]), site: { founderGrant: '0' }, clock: { t: LAUNCH + 1 } });
|
||||||
|
await lw.tick(); assert.ok(!Object.values(accounts.by).some(x => x.founder));
|
||||||
|
});
|
||||||
|
await test('accounts.js (JSON): touchSeen keeps the earlier visit as firstSeen; setFounder is once', async () => {
|
||||||
|
const dir = tmp(); delete process.env.DATABASE_URL;
|
||||||
|
const accts = require(path.join(ROOT, 'accounts.js')); accts.init({ dataDir: dir });
|
||||||
|
await accts.ensure('m@x.test', '', 'carried');
|
||||||
|
let a = await accts.byEmail('m@x.test'); assert.strictEqual(a.firstSeen, 0); assert.strictEqual(a.lastSeen, 0);
|
||||||
|
await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test'); const first = a.firstSeen; assert.ok(first > 0 && a.lastSeen === first);
|
||||||
|
await new Promise(r => setTimeout(r, 5)); await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test');
|
||||||
|
assert.strictEqual(a.firstSeen, first); assert.ok(a.lastSeen > first);
|
||||||
|
// an account that only has an old lastSeen (signed in before this field existed): its next visit keeps that time
|
||||||
|
const raw = JSON.parse(fs.readFileSync(path.join(dir, 'accounts.json'), 'utf8')); raw.byEmail['m@x.test'] = Object.assign(raw.byEmail['m@x.test'], { firstSeen: undefined, lastSeen: 12345 });
|
||||||
|
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(raw)); accts.init({ dataDir: dir });
|
||||||
|
await accts.touchSeen('m@x.test'); a = await accts.byEmail('m@x.test'); assert.strictEqual(a.firstSeen, 12345);
|
||||||
|
assert.deepStrictEqual(await accts.setFounder('m@x.test', LAUNCH), { ok: true }); assert.deepStrictEqual(await accts.setFounder('m@x.test', LAUNCH + 1), { ok: true, already: true });
|
||||||
|
assert.strictEqual((await accts.byEmail('m@x.test')).founder, LAUNCH);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('launchweek.test: public panel');
|
||||||
|
await test('panel hidden before the launch moment, shown from it, says POL to the wallet on file, no em dashes', async () => {
|
||||||
|
const clock = { t: LAUNCH - 1 };
|
||||||
|
const lw = instance({ accounts: fakeAccounts(ACCTS, POS), chain: fakeChain(WORLD), clock });
|
||||||
|
assert.strictEqual(await lw.panelHtml(), '');
|
||||||
|
clock.t = LAUNCH + 3 * 3600000; const h = await lw.panelHtml();
|
||||||
|
assert.ok(h.includes('Launch week contest') && h.includes('paid in POL to the wallet on file') && h.includes('at least 2'));
|
||||||
|
assert.ok(!/—/.test(h));
|
||||||
|
const pv = await lw.publicView(); assert.strictEqual(pv.contest.live, true); assert.deepStrictEqual(pv.contest.prizes, ['10', '6', '4']);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('\nlaunchweek.test: ' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// Conversion linkage, LinkSpin half (2026-11-07, reporting only). Throwaway data, no production data, nothing leaves the machine.
|
||||||
|
// 1) unit: netconv.js + convtrack.js + rotator.js on a temp dir: sign-up, wallet, purchases counted once with values; duplicate
|
||||||
|
// delivery; own account and own browser kept as tests; 30-day window by event time; first account owns the click; an event
|
||||||
|
// after the hit aged out of the rotator; InstantAdPay ad clicks; goals and events in one list without counting anything twice;
|
||||||
|
// per-link counts; postbacks once, never for a test.
|
||||||
|
// 2) two processes on one data dir (a deploy's overlap): the same events raced from both, each counted once, none lost.
|
||||||
|
// 3) browser (Playwright, if present): the landing tag on another origin decorates links to the network, directly and inside a
|
||||||
|
// redirect link (Orlando's go?c=...&u=... shape), keeps existing params, leaves other links alone, survives a page script
|
||||||
|
// that rewrites the link, and a stored id still decorates on a later page. Spin links are left alone.
|
||||||
|
// node qa/netconv.test.mjs Env: PORT (default 8983), PW
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const PORT = Number(process.env.PORT || 8983);
|
||||||
|
const DAY = 86400000;
|
||||||
|
let failed = 0, passed = 0; const out = [];
|
||||||
|
const check = (ok, what, detail) => { out.push((ok ? 'PASS ' : 'FAIL ') + what + (!ok && detail !== undefined ? ' :: ' + (typeof detail === 'string' ? detail : JSON.stringify(detail)) : '')); if (ok) passed++; else failed++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
const rq = (ip, ua) => ({ url: '/r/x', headers: { 'user-agent': ua || 'Mozilla/5.0 UnitUA', 'x-forwarded-for': ip }, socket: {} });
|
||||||
|
|
||||||
|
// ---------- 1) unit ----------
|
||||||
|
const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-unit-'));
|
||||||
|
const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js'));
|
||||||
|
M.init({ dataDir: UD });
|
||||||
|
const fired = [];
|
||||||
|
const P = { fire: async (o, ev, ctx) => { fired.push({ o, ev, ctx }); return []; } };
|
||||||
|
const initAll = () => { R.init({ dataDir: UD, ownHosts: () => ['linkspin.app'], wantsClickId: o => C.goalsOf(o).length > 0, isNetworkHost: h => ['instantadpay.com'].includes(h), goalRows: () => C.goalRows() }); C.init({ dataDir: UD, rotator: R, noTimers: true }); N.init({ dataDir: UD, convtrack: C, rotator: R, postbacks: P, marks: M, noTimers: true }); };
|
||||||
|
initAll();
|
||||||
|
const OWNER = 'orlando@u.test';
|
||||||
|
const rot = (await R.create(OWNER, { name: 'Bridge spin' })).rotation;
|
||||||
|
await R.addDest(OWNER, rot.id, { url: 'https://instantadpay.com/join/opgnetwerk', weight: 1 });
|
||||||
|
const hit = async ip => { const r = await R.resolve(rot.code, rq(ip)); return { id: r.lsid, url: r.url }; };
|
||||||
|
|
||||||
|
const a = await hit('198.51.100.1');
|
||||||
|
check(new URL(a.url).searchParams.get('lsclk') === a.id, 'a spin link straight at InstantAdPay carries lsclk with no goal set up', a.url);
|
||||||
|
const ev = (k, ev_, click, email, extra) => Object.assign({ k, ev: ev_, click, email, ts: Date.now() }, extra || {});
|
||||||
|
let r = await N.record(ev('join:a', 'join', a.id, 'lead1@u.test'));
|
||||||
|
check(r.result === 'counted', 'sign-up on a spin click counted', r);
|
||||||
|
check((await N.record(ev('join:a', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'the same sign-up delivered twice counts once');
|
||||||
|
check((await N.record(ev('join:other-key', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'a second sign-up on one click counts once');
|
||||||
|
check((await N.record(ev('wallet:a', 'wallet', a.id, 'lead1@u.test'))).result === 'counted', 'wallet link counted');
|
||||||
|
check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'counted', 'first purchase counted');
|
||||||
|
check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'dup', 'the same purchase delivered twice counts once');
|
||||||
|
check((await N.record(ev('purchase:0xb:1', 'purchase', a.id, 'lead1@u.test', { value: 20, tx: '0xb' }))).result === 'counted', 'a second package on the same click counts on its own');
|
||||||
|
let u = N.unified(OWNER, 30);
|
||||||
|
const row = (U, k) => (U.rows.find(x => x.k === k) || { n: 0, value: 0 });
|
||||||
|
check(row(u, 'join').n === 1 && row(u, 'wallet').n === 1 && row(u, 'purchase').n === 2 && row(u, 'purchase').value === 25, 'Reports: 1 join, 1 wallet, 2 purchases worth $25.00', u.rows);
|
||||||
|
check(u.buyers === 1, 'two packages by one click are one buyer', u.buyers);
|
||||||
|
const link = await R.get(OWNER, rot.id);
|
||||||
|
check(link.conversions === 4, 'the link shows 4 conversions', link.conversions);
|
||||||
|
const lst = await R.stats(OWNER, rot.id);
|
||||||
|
check(lst.conversions.some(x => /^purchase/.test(x.k) && x.n === 2), 'the link stats list both purchases', lst.conversions);
|
||||||
|
const sum = await R.summary(OWNER, 30);
|
||||||
|
check(sum.top[0].conv === 4, 'Reports top links: Conv. 4', sum.top[0]);
|
||||||
|
await N.syncMirror();
|
||||||
|
check(N.unified(OWNER, 30).rows.find(x => x.k === 'purchase').n === 2 && (await R.get(OWNER, rot.id)).conversions === 4, 'replaying the ledger into the rotator adds nothing');
|
||||||
|
check(fired.filter(f => f.ev === 'join').length === 1 && fired.filter(f => f.ev === 'purchase').length === 2, 'postbacks fire once per counted event', fired.map(f => f.ev));
|
||||||
|
check(fired.find(f => f.ev === 'purchase').ctx.payout === 5 && fired.find(f => f.ev === 'purchase').ctx.txid === '0xa', 'the purchase postback carries the value and the tx');
|
||||||
|
// a LinkSpin site join on the same click stays one join
|
||||||
|
await R.convert(a.id, 'join', {});
|
||||||
|
check(N.unified(OWNER, 30).rows.find(x => x.k === 'join').n === 1, 'a LinkSpin join on the same click does not add a second join');
|
||||||
|
|
||||||
|
// own account, own browser
|
||||||
|
const b = await hit('198.51.100.2'); fired.length = 0;
|
||||||
|
r = await N.record(ev('join:own', 'join', b.id, 'Orlando@U.test'));
|
||||||
|
check(r.result === 'self', "the click owner's own account is not counted", r);
|
||||||
|
r = await N.record(ev('purchase:0xself:1', 'purchase', b.id, 'orlando@u.test', { value: 100 }));
|
||||||
|
check(r.result === 'self' && fired.length === 0, 'its purchases are not counted and fire no postback', r);
|
||||||
|
const c1 = await hit('198.51.100.3'); const skO = C.softKey(rq('192.0.2.7', 'OwnerUA')); C.noteOwner(OWNER, skO);
|
||||||
|
check((await N.record(ev('join:ownsk', 'join', c1.id, 'stranger1@u.test', { sk: skO }))).result === 'self', "a sign-up from a browser the owner signs in from is a test");
|
||||||
|
check((await N.record(ev('purchase:0xownsk:1', 'purchase', c1.id, 'stranger1@u.test', { value: 9 }))).result === 'self', 'and stays one on that click');
|
||||||
|
const c2 = await hit('198.51.100.4'); C.markSelfClick(c2.id, OWNER, rq('1.1.1.1'), OWNER);
|
||||||
|
check((await N.record(ev('join:ownclick', 'join', c2.id, 'stranger2@u.test'))).result === 'self', "the owner's own click is a test");
|
||||||
|
check(row(N.unified(OWNER, 30), 'purchase').value === 25, 'none of that moved the totals');
|
||||||
|
|
||||||
|
// window, unknown clicks, first account
|
||||||
|
const d2 = await hit('198.51.100.6'); const hd2 = R.hitById(d2.id).hit; hd2.ts = Date.now() - 31 * DAY;
|
||||||
|
check((await N.record(ev('join:late', 'join', d2.id, 'late2@u.test'))).result === 'expired', 'an event more than 30 days after the click does not count');
|
||||||
|
const d3 = await hit('198.51.100.7'); R.hitById(d3.id).hit.ts = Date.now() - 31 * DAY;
|
||||||
|
check((await N.record(ev('join:latedelivery', 'join', d3.id, 'late3@u.test', { ts: Date.now() - 2 * DAY }))).result === 'counted', 'the window runs to the event, so a delayed delivery still counts');
|
||||||
|
check((await N.record(ev('join:nosuch', 'join', 'abcdef0123', 'x@u.test'))).result === 'nomatch', 'an unknown click is refused');
|
||||||
|
check((await N.record(ev('join:bad', 'nonsense', a.id, 'x@u.test'))).result === 'bad' && (await N.record({ k: 'x' })).result === 'bad', 'bad events are refused');
|
||||||
|
const e1 = await hit('198.51.100.8');
|
||||||
|
await N.record(ev('join:first', 'join', e1.id, 'first@u.test'));
|
||||||
|
check((await N.record(ev('purchase:0xsecond:1', 'purchase', e1.id, 'second@u.test', { value: 5 }))).result === 'other', 'a click belongs to the first account on it');
|
||||||
|
|
||||||
|
// the hit ages out of the rotator: later events still count on the link
|
||||||
|
const f = await hit('198.51.100.9');
|
||||||
|
await N.record(ev('join:aged', 'join', f.id, 'aged@u.test'));
|
||||||
|
{ const file = path.join(UD, 'rotator.json'); const db = JSON.parse(fs.readFileSync(file, 'utf8')); db.hits = db.hits.filter(h => h.id !== f.id); fs.writeFileSync(file, JSON.stringify(db)); initAll(); }
|
||||||
|
check(!R.hitById(f.id), 'the hit is gone from the rotator');
|
||||||
|
const before = (await R.get(OWNER, rot.id)).conversions;
|
||||||
|
check((await N.record(ev('purchase:0xaged:1', 'purchase', f.id, 'aged@u.test', { value: 50 }))).result === 'counted', 'a purchase after the hit aged out still counts');
|
||||||
|
check((await R.get(OWNER, rot.id)).conversions === before + 1, 'and lands on the link');
|
||||||
|
|
||||||
|
// InstantAdPay ad click: no rotator, in the ledger, on the campaign
|
||||||
|
C.importClicks([{ id: 'i0123456789a', camp: 7, cname: 'My ad', owner: 'adv@u.test', ts: Date.now(), sk: '', type: 'banner' }]);
|
||||||
|
check((await N.record(ev('join:ad', 'join', 'i0123456789a', 'adlead@u.test'))).result === 'counted', 'an InstantAdPay ad click counts');
|
||||||
|
await N.record(ev('purchase:0xad:1', 'purchase', 'i0123456789a', 'adlead@u.test', { value: 20 }));
|
||||||
|
const pa = N.partner('adv@u.test', 30);
|
||||||
|
check(pa.byCampaign[7] && pa.byCampaign[7].join === 1 && pa.byCampaign[7].purchase === 1 && pa.byCampaign[7].value === 20, 'the campaign shows its join and purchase', pa.byCampaign);
|
||||||
|
check(row(N.unified('adv@u.test', 30), 'purchase').value === 20, 'ad events are in the one list (not in the rotator)');
|
||||||
|
check((await N.record(ev('join:adown', 'join', 'i0123456789a', 'adv@u.test'))).result !== 'counted', "the ad owner's own account is not counted");
|
||||||
|
|
||||||
|
// goals and events in one list; a goal is not an event and nothing is listed twice
|
||||||
|
const g = C.createGoal(OWNER, { name: 'subscriber', value: '2' }); const px = g.goal.px;
|
||||||
|
const gh = await hit('198.51.100.10');
|
||||||
|
const fake = { headers: { 'user-agent': 'GoalUA', 'x-forwarded-for': '198.51.100.11' }, socket: {} };
|
||||||
|
check(C.record({ px, c: gh.id, m: 'url' }, fake, {}).result === 'counted', 'a goal converts on a spin click');
|
||||||
|
await N.record(ev('join:gh', 'join', gh.id, 'goalman@u.test'));
|
||||||
|
const U2 = N.unified(OWNER, 30);
|
||||||
|
check(row(U2, 'goal:subscriber').n === 1 && row(U2, 'goal:subscriber').value === 2, 'goals are in the one list with their value', U2.rows);
|
||||||
|
const before2 = (await R.get(OWNER, rot.id));
|
||||||
|
check(before2.conversions >= 2 && before2.convBy['goal: subscriber'] === 1, 'per-link counts include goals', before2.convBy);
|
||||||
|
const s2 = await R.summary(OWNER, 30);
|
||||||
|
check(s2.conversions.filter(x => x.k === 'goal: subscriber').length === 1, 'and the top-links count sees it once');
|
||||||
|
|
||||||
|
// ---------- 2) two processes, one data dir ----------
|
||||||
|
{
|
||||||
|
const worker = path.join(UD, 'worker.cjs'); const DD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-race-'));
|
||||||
|
fs.writeFileSync(worker, `
|
||||||
|
const path = require('path'); const site = ${JSON.stringify(site)}; const DD = ${JSON.stringify(DD)};
|
||||||
|
const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js'));
|
||||||
|
M.init({ dataDir: DD }); R.init({ dataDir: DD, ownHosts: () => [] }); C.init({ dataDir: DD, rotator: R, noTimers: true }); N.init({ dataDir: DD, convtrack: C, rotator: R, marks: M, noTimers: true });
|
||||||
|
(async () => { const until = Number(process.argv[2]); while (Date.now() < until) await new Promise(r => setTimeout(r, 5));
|
||||||
|
const out = []; for (let i = 0; i < 40; i++) out.push((await N.record({ k: 'purchase:0xrace:' + i, ev: 'purchase', click: 'abcdef0123', email: 'race@u.test', value: 1, ts: Date.now() })).result);
|
||||||
|
out.push((await N.record({ k: 'join:race', ev: 'join', click: 'abcdef0123', email: 'race@u.test', ts: Date.now() })).result);
|
||||||
|
process.stdout.write(JSON.stringify(out)); })().catch(e => { process.stdout.write(JSON.stringify({ error: e.message })); }); `);
|
||||||
|
const seed = { v: 1, rotations: [{ id: 1, owner: 'race-owner@u.test', name: 'r', code: 'raceee', fallback: '', destinations: [], created: Date.now(), paused: false, nextDest: 1 }], hits: [{ id: 'abcdef0123', r: 1, d: 0, ts: Date.now(), v: 'x', c: '', s: 'direct', dv: 'desktop', bot: 0 }], conv: [] };
|
||||||
|
fs.writeFileSync(path.join(DD, 'rotator.json'), JSON.stringify(seed));
|
||||||
|
const until = Date.now() + 1200;
|
||||||
|
const run = () => new Promise(res => { const p = spawn(process.execPath, [worker, String(until)], { stdio: ['ignore', 'pipe', 'inherit'] }); let o = ''; p.stdout.on('data', c => o += c); p.on('close', () => { try { res(JSON.parse(o)); } catch (e) { res({ error: o }); } }); });
|
||||||
|
const [x, y] = await Promise.all([run(), run()]);
|
||||||
|
const all = [].concat(x, y);
|
||||||
|
check(Array.isArray(x) && Array.isArray(y), 'both copies ran', { x, y });
|
||||||
|
check(all.filter(v => v === 'counted').length === 41, '41 events raced from two copies: exactly 41 counted', all.filter(v => v === 'counted').length);
|
||||||
|
const rows = fs.readFileSync(path.join(DD, 'netconv.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
|
||||||
|
check(rows.length === 41 && new Set(rows.map(r => r.k)).size === 41, 'the ledger holds each event once, none lost', rows.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 3) the landing tag in a browser, on another origin ----------
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
if (fs.existsSync(PW)) {
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-b-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest', SITE_HOST: '127.0.0.1:' + PORT });
|
||||||
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY', 'LS_SYNC_SECRET']) delete env[k];
|
||||||
|
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: 'ignore' });
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 40; i++) { try { const r = await fetch('http://127.0.0.1:' + PORT + '/t.js', { signal: AbortSignal.timeout(2000) }); if (r.ok) break; } catch (e) {} await sleep(500); }
|
||||||
|
const tag = await (await fetch('http://127.0.0.1:' + PORT + '/t.js')).text();
|
||||||
|
check(/"instantadpay\.com"/.test(tag) && !tag.includes('/*ls-net*/'), '/t.js is served with the network host list filled in');
|
||||||
|
const pw = require(PW); const br = await pw.chromium.launch(); const ctx = await br.newContext(); const page = await ctx.newPage();
|
||||||
|
const errors = []; page.on('pageerror', e => errors.push(e.message));
|
||||||
|
const BTN = 'https://go.opgnetwerk.test/go?c=bridge-a&u=https%3A%2F%2Finstantadpay.com%2Fjoin%2Fopgnetwerk&keep=a%20b';
|
||||||
|
const html = `<!doctype html><title>bridge</title><body>
|
||||||
|
<a id="wrap" class="cta" data-c="x" href="${BTN.replace(/&/g, '&')}">IAP through a redirect</a>
|
||||||
|
<a id="wrapls" href="https://go.opgnetwerk.test/go?c=b&u=http%3A%2F%2F127.0.0.1%2Fjoin%2Fopgnetwerk">LinkSpin through a redirect</a>
|
||||||
|
<a id="direct" href="https://instantadpay.com/join/opgnetwerk?v=play#top">direct</a>
|
||||||
|
<a id="share" href="https://www.instantadpay.link/opgnetwerk">share domain</a>
|
||||||
|
<a id="has" href="https://instantadpay.com/join/x?lsclk=abcdef0123">already has one</a>
|
||||||
|
<a id="spin" href="http://127.0.0.1/r/abc123">spin link</a>
|
||||||
|
<a id="other" href="https://bix.example/?a=1">other site</a>
|
||||||
|
<a id="wrapother" href="https://go.opgnetwerk.test/go?u=https%3A%2F%2Fbix.example%2F">redirect to another site</a>
|
||||||
|
<a id="skip" data-ls-skip href="https://instantadpay.com/join/y">opted out</a>
|
||||||
|
<a id="anchor" href="#sec">anchor</a><a id="late-target" href="/next">next</a>
|
||||||
|
<script>var s=new URLSearchParams(location.search).get('src');if(s){var a=document.getElementById('wrap'),h=a.getAttribute('href'),q=h.indexOf('?'),p=new URLSearchParams(h.slice(q+1));p.set('c','x-'+s);a.setAttribute('href',h.slice(0,q)+'?'+p.toString());}</script>
|
||||||
|
<script async src="http://127.0.0.1:${PORT}/t.js?px=px0123456789"></script><script async src="http://127.0.0.1:${PORT}/t.js?px=pxabcdef0123"></script></body>`;
|
||||||
|
const later = '<!doctype html><title>next</title><body><a id="direct" href="https://instantadpay.com/join/opgnetwerk">x</a><script async src="http://127.0.0.1:' + PORT + '/t.js?px=px0123456789"></script></body>';
|
||||||
|
const noid = html;
|
||||||
|
const bridge = http.createServer((q, s) => { s.writeHead(200, { 'Content-Type': 'text/html' }); s.end(new URL(q.url, 'http://x').pathname === '/next' ? later : noid); }).listen(PORT + 1);
|
||||||
|
const BR = 'http://localhost:' + (PORT + 1);
|
||||||
|
const ID = 'abc123def0';
|
||||||
|
await page.goto(BR + '/lp?src=banner&lsclk=' + ID); await sleep(700);
|
||||||
|
const hrefOf = sel => page.$eval(sel, a => a.href);
|
||||||
|
const wrap = await hrefOf('#wrap'); const wu = new URL(wrap);
|
||||||
|
check(new URL(wu.searchParams.get('u')).searchParams.get('lsclk') === ID, "Orlando's redirect link: the click id is inside the u address", wrap);
|
||||||
|
check(new URL(wu.searchParams.get('u')).pathname === '/join/opgnetwerk' && wu.searchParams.get('c') === 'x-banner', 'the redirect link keeps its address and its other params', wrap);
|
||||||
|
check(new URL(new URL(await hrefOf('#wrapls')).searchParams.get('u')).searchParams.get('lsclk') === ID, 'the LinkSpin button through the redirect too');
|
||||||
|
check(await hrefOf('#direct') === 'https://instantadpay.com/join/opgnetwerk?v=play&lsclk=' + ID + '#top', 'a direct link: existing param and #hash stay', await hrefOf('#direct'));
|
||||||
|
check(new URL(await hrefOf('#share')).searchParams.get('lsclk') === ID, 'share domains are network hosts (www stripped)');
|
||||||
|
check(await hrefOf('#has') === 'https://instantadpay.com/join/x?lsclk=abcdef0123', 'a link already carrying a click id is left alone');
|
||||||
|
check(await hrefOf("#spin").then(h => h.split("127.0.0.1")[1]) === "/r/abc123", 'spin links are left alone, they make their own click');
|
||||||
|
check(await hrefOf('#other') === 'https://bix.example/?a=1' && !/lsclk/.test(await hrefOf('#wrapother')), 'other sites are left alone, redirected or not');
|
||||||
|
check(await hrefOf('#skip') === 'https://instantadpay.com/join/y', 'data-ls-skip is respected');
|
||||||
|
await page.click('#late-target'); await sleep(600);
|
||||||
|
check(new URL(page.url()).searchParams.get('lsclk') === ID, 'same-site links still carry it, as before');
|
||||||
|
await page.goto(BR + '/next'); await sleep(600);
|
||||||
|
check(new URL(await hrefOf('#direct')).searchParams.get('lsclk') === ID, 'a later page with no id in the address: the stored id still decorates');
|
||||||
|
// a foreign clickid is not one of ours: stored as before, never carried to the network
|
||||||
|
const c2x = await br.newContext(); const p2 = await c2x.newPage();
|
||||||
|
await p2.goto(BR + '/lp?clickid=foreign12345678'); await sleep(600);
|
||||||
|
check(await p2.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', "another network's clickid never travels to the network");
|
||||||
|
// no id at all: the page is untouched
|
||||||
|
const c3x = await br.newContext(); const p3 = await c3x.newPage();
|
||||||
|
await p3.goto(BR + '/lp'); await sleep(500);
|
||||||
|
check(await p3.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', 'no click id: links untouched');
|
||||||
|
check(errors.length === 0, 'no page errors', errors);
|
||||||
|
await br.close(); bridge.close();
|
||||||
|
} finally { srv.kill(); }
|
||||||
|
} else out.push('SKIP browser part (no Playwright at ' + PW + ')');
|
||||||
|
|
||||||
|
console.log(out.join('\n'));
|
||||||
|
console.log('\n' + passed + ' passed, ' + failed + ' failed');
|
||||||
|
process.exit(failed ? 1 : 0);
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12) end to end: boots BOTH servers locally on throwaway DATA_DIRs and drives
|
||||||
|
// a real browser across them. Same file in both repos. node qa/networksso.e2e.mjs
|
||||||
|
// The other repo is found at NSSO_PEER_DIR, else ../../linkspin/site or ../../onchain-ad-membership/site from this site dir.
|
||||||
|
// InstantAdPay runs on http://127.0.0.1:<port> and LinkSpin on http://localhost:<port>: two hosts, so the two sites' cookies
|
||||||
|
// stay apart like instantadpay.com and linkspin.app do. No mail key on either copy (no email can leave), JSON stores, devCode.
|
||||||
|
// Proves: IAP -> LinkSpin and LinkSpin -> IAP arrive signed in without a code; the silent check on a sign-in page (signed in on
|
||||||
|
// the other site -> in; not -> the normal sign-in, one bounce only); signed out on the other site -> normal sign-in; a replayed or
|
||||||
|
// expired token is refused; an email not on the receiving site yet gets the email-code form prefilled, nothing created; sign-out
|
||||||
|
// stays per site; bots never bounce; no email-code request is made by any network sign-in.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||||
|
const peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
|
||||||
|
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||||
|
if (!PEER || !fs.existsSync(path.join(IAP_DIR, 'networksso.js')) || !fs.existsSync(path.join(LS_DIR, 'networksso.js'))) {
|
||||||
|
console.log('SKIP network sign-in e2e: the other repo (with networksso.js) was not found. Set NSSO_PEER_DIR.'); process.exit(0);
|
||||||
|
}
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const SECRET = crypto.randomBytes(24).toString('hex');
|
||||||
|
const IP = Number(process.env.NSSO_IAP_PORT || 8821), LP = Number(process.env.NSSO_LS_PORT || 8822);
|
||||||
|
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP;
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-'));
|
||||||
|
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
|
||||||
|
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||||
|
fs.writeFileSync(SPY, "const http=require('http');const e=http.Server.prototype.emit;http.Server.prototype.emit=function(ev,req){if(ev==='request'&&req&&req.url)process.stdout.write('REQ '+req.method+' '+String(req.url).split('?')[0]+'\\n');return e.apply(this,arguments);};\n");
|
||||||
|
const logs = { iap: '', ls: '' };
|
||||||
|
function boot(name, dir, port, extra) {
|
||||||
|
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||||
|
NETWORK_SSO_SECRET: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', LS_SYNC_SECRET: '', NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, extra);
|
||||||
|
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||||
|
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||||
|
}
|
||||||
|
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
|
||||||
|
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
|
||||||
|
const reqs = name => logs[name].split('\n').filter(l => l.startsWith('REQ '));
|
||||||
|
const codeReqs = () => reqs('iap').concat(reqs('ls')).filter(l => /\/api\/auth\/email\/(start|verify)$/.test(l)).length;
|
||||||
|
|
||||||
|
// sign in through the email code over plain HTTP (a separate client: its own IP via x-forwarded-for, its own device)
|
||||||
|
let ipN = 10;
|
||||||
|
async function codeSignIn(base, email) {
|
||||||
|
const h = { 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA };
|
||||||
|
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||||
|
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||||
|
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||||
|
const sid = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid='));
|
||||||
|
if (!sid) throw new Error('code sign-in failed on ' + base + ' for ' + email + ': ' + JSON.stringify(sj) + ' / ' + v.status + ' ' + (await v.text()).slice(0, 200));
|
||||||
|
return sid.slice('iap.sid='.length);
|
||||||
|
}
|
||||||
|
const meOf = async (ctx, base) => { const r = await ctx.request.get(base + '/api/me', { headers: { Accept: 'application/json' } }); try { return await r.json(); } catch (e) { return {}; } };
|
||||||
|
async function newCtx(sessions) {
|
||||||
|
const ctx = await browser.newContext({ userAgent: UA });
|
||||||
|
const add = [];
|
||||||
|
if (sessions && sessions.iap) add.push({ name: 'iap.sid', value: sessions.iap, domain: '127.0.0.1', path: '/' });
|
||||||
|
if (sessions && sessions.ls) add.push({ name: 'iap.sid', value: sessions.ls, domain: 'localhost', path: '/' });
|
||||||
|
if (add.length) await ctx.addCookies(add);
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
let browser = null;
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 60; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; await sleep(500); }
|
||||||
|
browser = await chromium.launch();
|
||||||
|
// members: A and B have accounts on both sites, C only on InstantAdPay, D only on LinkSpin
|
||||||
|
const A = 'nsso-a@example.com', B = 'nsso-b@example.com', C = 'nsso-c@example.com', D = 'nsso-d@example.com';
|
||||||
|
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
|
||||||
|
const bL = await codeSignIn(LS, B); await codeSignIn(IAP, B);
|
||||||
|
const cI = await codeSignIn(IAP, C);
|
||||||
|
const dL = await codeSignIn(LS, D);
|
||||||
|
const codes0 = codeReqs();
|
||||||
|
|
||||||
|
// 1. IAP -> LinkSpin through the /go hop
|
||||||
|
let ctx = await newCtx({ iap: aI }); let page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/ads'));
|
||||||
|
await page.waitForLoadState('domcontentloaded');
|
||||||
|
let me = await meOf(ctx, LS);
|
||||||
|
ok(page.url() === LS + '/ads' && me.signedIn && me.email === A, 'IAP -> LinkSpin: lands on /ads signed in as the same member, no code', page.url() + ' ' + JSON.stringify({ s: me.signedIn, e: me.email }));
|
||||||
|
ok((await meOf(ctx, IAP)).email === A, 'IAP session untouched');
|
||||||
|
// sign-out on LinkSpin stays on LinkSpin, and the silent check does not sign them straight back in
|
||||||
|
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||||
|
await page.goto(LS + '/ads'); await page.waitForTimeout(2500);
|
||||||
|
me = await meOf(ctx, LS);
|
||||||
|
ok(!me.signedIn && page.url() === LS + '/ads', 'signed out on LinkSpin: stays signed out there (no automatic sign-in back)', page.url());
|
||||||
|
ok((await meOf(ctx, IAP)).email === A, 'signing out of LinkSpin leaves InstantAdPay signed in');
|
||||||
|
// a deliberate link from IAP still signs them in after the sign-out
|
||||||
|
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/credits?from=iap&task=refuel#refuel')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
me = await meOf(ctx, LS);
|
||||||
|
ok(me.email === A && page.url() === LS + '/credits?from=iap&task=refuel#refuel', 'after a sign-out, a link from InstantAdPay signs in again and keeps the query and hash', page.url());
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 2. LinkSpin -> IAP through the /go hop (dashboard gets ?welcome=1, the step a code sign-in takes for the login ad)
|
||||||
|
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||||
|
const navs = []; page.on('framenavigated', f => { if (f === page.mainFrame()) navs.push(f.url()); });
|
||||||
|
await page.goto(LS + '/go/iap?to=' + encodeURIComponent('/my#engine')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
me = await meOf(ctx, IAP);
|
||||||
|
ok(me.signedIn && me.email === B && navs.some(u => u.startsWith(IAP + '/my?welcome=1#engine')), 'LinkSpin -> IAP: lands on /my#engine signed in as the same member, no code', navs.slice(-2).join(' , '));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 3. silent check: signed in on IAP, open a LinkSpin screen directly
|
||||||
|
ctx = await newCtx({ iap: aI }); page = await ctx.newPage();
|
||||||
|
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 15000 }); await page.waitForTimeout(2500);
|
||||||
|
me = await meOf(ctx, LS);
|
||||||
|
ok(me.email === A && page.url() === LS + '/links', 'silent check: a LinkSpin screen opened directly signs in through IAP', page.url());
|
||||||
|
await ctx.close();
|
||||||
|
// and the other way: signed in on LinkSpin, open the IAP dashboard
|
||||||
|
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForTimeout(4000);
|
||||||
|
me = await meOf(ctx, IAP);
|
||||||
|
ok(me.email === B && page.url().startsWith(IAP + '/my'), 'silent check: the IAP sign-in page signs in through LinkSpin', page.url());
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 4. silent check, signed in nowhere: one bounce, then the normal sign-in; no second bounce on reload
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage();
|
||||||
|
const starts = []; page.on('request', r => { if (r.url().includes('/sso/start')) starts.push(r.url()); });
|
||||||
|
await page.goto(LS + '/ads'); await page.waitForTimeout(3000);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
||||||
|
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
||||||
|
await page.reload(); await page.waitForTimeout(2500);
|
||||||
|
ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
||||||
|
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 5. expired / absent session on the provider: signed out on IAP, the /go link is a plain link and LinkSpin asks for the code
|
||||||
|
const aI2 = await codeSignIn(IAP, A);
|
||||||
|
ctx = await newCtx({ iap: aI2 }); page = await ctx.newPage();
|
||||||
|
await ctx.request.post(IAP + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||||
|
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForTimeout(2500);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'signed out on IAP: /go/linkspin is a plain link, LinkSpin shows its sign-in', page.url());
|
||||||
|
await ctx.close();
|
||||||
|
// a session that expired on the provider: the check answers none
|
||||||
|
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
|
||||||
|
await page.goto(LS + '/sso/start?mode=go&to=%2Fads'); await page.waitForTimeout(1500);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'an expired IAP session: the check answers none, normal sign-in');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
||||||
|
ctx = await newCtx({ iap: cI }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForSelector('#siEmail', { timeout: 10000 }); await page.waitForTimeout(1500);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && (await page.inputValue('#siEmail')) === C && (await page.locator('#nssoNote').count()) === 1, 'IAP member not on LinkSpin yet: LinkSpin sign-in with the email filled in, nothing signed', await page.inputValue('#siEmail'));
|
||||||
|
ok(!fs.readFileSync(path.join(TMP, 'ls', 'accounts.json'), 'utf8').includes(C), 'no LinkSpin account was created by the network sign-in');
|
||||||
|
await ctx.close();
|
||||||
|
ctx = await newCtx({ ls: dL }); page = await ctx.newPage();
|
||||||
|
await page.goto(LS + '/go/iap?to=%2Fmy'); await page.waitForTimeout(4000);
|
||||||
|
ok(!(await meOf(ctx, IAP)).signedIn && page.url().startsWith(IAP + '/my') && (await page.inputValue('#mcEmail').catch(() => '')) === D, 'LinkSpin member not on IAP yet: IAP sign-in with the email filled in, nothing signed', page.url() + ' ' + (await page.inputValue('#mcEmail').catch(() => '?')));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 7. replay: walk the hops by hand, spend the token once, then try it again with the state cookie put back
|
||||||
|
const aI3 = await codeSignIn(IAP, A);
|
||||||
|
ctx = await newCtx({ iap: aI3 });
|
||||||
|
const hop = async url => { const r = await ctx.request.get(url, { maxRedirects: 0, headers: { 'User-Agent': UA, 'sec-fetch-dest': 'document' } }); return r.headers()['location'] || ''; };
|
||||||
|
let loc = await hop(LS + '/sso/start?mode=go&to=%2Fads');
|
||||||
|
const st = (await ctx.cookies(LS)).find(c => c.name === 'nsso.st');
|
||||||
|
loc = await hop(loc.startsWith('http') ? loc : LS + loc);
|
||||||
|
ok(/^http:\/\/localhost:\d+\/sso\/in\?t=v1\./.test(loc), 'provider minted a token for LinkSpin', loc.slice(0, 60));
|
||||||
|
const tokUrl = loc;
|
||||||
|
let land = await hop(tokUrl);
|
||||||
|
ok(land === '/ads' && (await meOf(ctx, LS)).email === A, 'first use signs in');
|
||||||
|
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||||
|
await ctx.addCookies([{ name: 'nsso.st', value: st.value, domain: 'localhost', path: '/' }]);
|
||||||
|
land = await hop(tokUrl);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && /token already used/.test(logs.ls), 'the same token again is refused (replay), even with the state cookie put back', land);
|
||||||
|
// a token from a different browser (state cookie missing) is refused: login CSRF
|
||||||
|
const ctx2 = await newCtx({ iap: aI3 });
|
||||||
|
const r2 = await ctx2.request.get(LS + '/sso/start?mode=go&to=%2Fads', { maxRedirects: 0, headers: { 'sec-fetch-dest': 'document' } });
|
||||||
|
const l2 = await ctx2.request.get(r2.headers()['location'], { maxRedirects: 0 });
|
||||||
|
const other = await newCtx(); const r3 = await other.request.get(l2.headers()['location'], { maxRedirects: 0 });
|
||||||
|
ok(!(await meOf(other, LS)).signedIn && /refused: state/.test(logs.ls), 'a token opened in another browser (no matching state) is refused', r3.headers()['location']);
|
||||||
|
await ctx2.close(); await other.close();
|
||||||
|
// an expired token (minted by hand with a past clock) is refused
|
||||||
|
const require = createRequire(import.meta.url); process.env.NETWORK_SSO_SECRET = SECRET;
|
||||||
|
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||||
|
const st2 = crypto.randomBytes(16).toString('hex');
|
||||||
|
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]);
|
||||||
|
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
||||||
|
await hop(LS + '/sso/in?t=' + old);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
||||||
|
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/.$/, c => c === 'A' ? 'B' : 'A');
|
||||||
|
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
|
||||||
|
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
|
||||||
|
// open redirect: an off-site path never leaves the site
|
||||||
|
const ev = await hop(IAP + '/go/linkspin?to=' + encodeURIComponent('https://evil.example/x'));
|
||||||
|
ok(ev === LS + '/sso/start?mode=go&to=%2F', '/go with an off-site path stays on the network', ev);
|
||||||
|
const ev2 = await ctx.request.get(LS + '/sso/in?none=1&to=' + encodeURIComponent('//evil.example'), { maxRedirects: 0 });
|
||||||
|
ok(ev2.headers()['location'] === '/ads', '/sso/in never redirects off the site', ev2.headers()['location']);
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 8. bots and API calls never bounce
|
||||||
|
const bot = await fetch(LS + '/sso/start?to=%2Fads', { redirect: 'manual', headers: { 'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)' } });
|
||||||
|
ok(bot.headers.get('location') === '/ads' && !(bot.headers.getSetCookie ? bot.headers.getSetCookie() : []).length, 'a crawler on /sso/start goes straight to the page');
|
||||||
|
const bs = await (await fetch(IAP + '/api/sso/status', { headers: { 'User-Agent': 'Googlebot/2.1' } })).json();
|
||||||
|
ok(bs.check === false, 'a crawler is never told to check');
|
||||||
|
|
||||||
|
// 9. no email-code request was made by any network sign-in (only the setup code sign-ins above)
|
||||||
|
const total = codeReqs();
|
||||||
|
ok(total === codes0 + 4, 'no email-code request made by any network sign-in (server request log: only the 2 later setup sign-ins, start + verify each)', 'before ' + codes0 + ', after ' + total);
|
||||||
|
ok(!/sendCode|sendgrid/i.test(logs.iap + logs.ls), 'no mail send attempted on either server');
|
||||||
|
ok(/network-sso signed in from InstantAdPay n\*\*\*@example\.com/.test(logs.ls) && /network-sso signed in from LinkSpin n\*\*\*@example\.com/.test(logs.iap), 'successes logged with the email masked');
|
||||||
|
ok(!logs.iap.includes(SECRET) && !logs.ls.includes(SECRET) && !/nsso-a@example\.com/.test((logs.iap + logs.ls).split('\n').filter(l => l.includes('network-sso')).join('\n')), 'no secret and no full email in the network sign-in log lines');
|
||||||
|
} catch (e) { console.log('FAIL exception', e && e.stack || e); fails++; }
|
||||||
|
finally {
|
||||||
|
try { if (browser) await browser.close(); } catch (e) {}
|
||||||
|
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {}
|
||||||
|
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (network-sso / errors)\n' + logs[k].split('\n').filter(l => /network-sso|error|Error/.test(l)).slice(-25).join('\n')); }
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12): unit test of networksso.js. Same file in both repos. node qa/networksso.test.cjs
|
||||||
|
// Token sign/verify, expiry, clock skew, tamper, wrong audience, state binding, replay, the secret switch, open redirects,
|
||||||
|
// bots, and the route handler with fake requests (no server, no network, throwaway DATA_DIR).
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'), os = require('os'), path = require('path'), crypto = require('crypto');
|
||||||
|
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||||
|
const N = require('../networksso.js');
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-unit-'));
|
||||||
|
const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const sessions = { 'tok-a': { email: 'a@example.com' } };
|
||||||
|
const accounts = new Set(['a@example.com']);
|
||||||
|
const signedIn = [];
|
||||||
|
N.init({ self: 'iap', peer: 'linkspin', peerBase: () => 'https://ls.example', isProd: true, dataDir: DATA, db: null, defaultPath: '/my',
|
||||||
|
member: async req => sessions[(/sid=([^;]+)/.exec(req.headers.cookie || '') || [])[1]] || null,
|
||||||
|
accept: async e => accounts.has(e) ? { ok: true } : { fallback: 'no account here yet' },
|
||||||
|
signIn: async e => { signedIn.push(e); return 'iap.sid=new; Path=/; HttpOnly'; },
|
||||||
|
landing: to => to, signinPath: to => '/my' });
|
||||||
|
|
||||||
|
// ---- tokens ----
|
||||||
|
const t = N.mint({ iss: 'linkspin', aud: 'iap', email: 'A@Example.com', st, to: '/my#buy' });
|
||||||
|
let v = N.verify(t, { iss: 'linkspin', aud: 'iap', st });
|
||||||
|
ok(v.ok && v.email === 'a@example.com' && v.to === '/my#buy', 'round trip: email (lower-cased) and path come back', JSON.stringify(v));
|
||||||
|
ok(/^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(t), 'token format v1.<payload>.<hmac>');
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'linkspin', st }).error === 'audience', 'wrong audience refused');
|
||||||
|
ok(N.verify(t, { iss: 'iap', aud: 'iap', st }).error === 'audience', 'wrong issuer refused');
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 61000 }).error === 'expired', 'expired after 60 s');
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 55000 }).ok, 'still good at 55 s');
|
||||||
|
const fut = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: '/', now: Date.now() + 120000 });
|
||||||
|
ok(N.verify(fut, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'issued too far in the future refused');
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: crypto.randomBytes(16).toString('hex') }).error === 'state', 'state from another browser refused');
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: '' }).error === 'state', 'missing state cookie refused');
|
||||||
|
const [, body, mac] = t.split('.');
|
||||||
|
const pl = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString()); pl.email = 'evil@example.com';
|
||||||
|
ok(N.verify('v1.' + b64u(JSON.stringify(pl)) + '.' + mac, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'payload tampered (email swapped) refused');
|
||||||
|
ok(N.verify('v1.' + body + '.' + (mac[0] === 'A' ? 'B' : 'A') + mac.slice(1), { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'signature tampered refused');
|
||||||
|
const longer = JSON.parse(JSON.stringify(pl)); longer.email = 'a@example.com'; longer.exp = longer.iat + 3600000;
|
||||||
|
const forged = 'v1.' + b64u(JSON.stringify(longer)) + '.' + b64u(crypto.createHmac('sha256', process.env.NETWORK_SSO_SECRET).update('nsso.v1.' + b64u(JSON.stringify(longer))).digest());
|
||||||
|
ok(N.verify(forged, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'a validly signed token with a life over 60 s is refused');
|
||||||
|
ok(N.verify('garbage', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed' && N.verify('', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed', 'garbage refused');
|
||||||
|
process.env.NETWORK_SSO_SECRET = 'w'.repeat(48);
|
||||||
|
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'another secret refused');
|
||||||
|
process.env.NETWORK_SSO_SECRET = 'short';
|
||||||
|
ok(!N.enabled() && N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'off', 'secret under 32 characters = switched off');
|
||||||
|
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||||
|
|
||||||
|
// ---- replay ----
|
||||||
|
ok(await N.spend(v.n, v.exp) === true, 'first use of a nonce is spent');
|
||||||
|
ok(await N.spend(v.n, v.exp) === false, 'second use of the same nonce refused (replay)');
|
||||||
|
ok(JSON.parse(fs.readFileSync(path.join(DATA, 'network-sso-nonces.json'), 'utf8'))[v.n] > 0, 'spent nonce kept on disk (survives a restart inside the window)');
|
||||||
|
|
||||||
|
// ---- open redirects ----
|
||||||
|
const bad = ['https://evil.example/x', '//evil.example/x', '/\\evil.example', '\\\\evil.example', 'javascript:alert(1)', '/x\r\nSet-Cookie: a=b', ' /my', '/my\t', 'http:/evil.example', '/' + 'a'.repeat(700), '', null];
|
||||||
|
ok(bad.every(b => N.safePath(b, '/my') === '/my'), 'off-site, protocol-relative, backslash, script, header-injection and over-long paths fall back to the default', bad.map(b => N.safePath(b, '/my')).filter(x => x !== '/my').join(' | '));
|
||||||
|
ok(N.safePath('/credits?from=iap&task=refuel#refuel') === '/credits?from=iap&task=refuel#refuel' && N.safePath('/my#buy') === '/my#buy', 'same-site paths with query and hash pass');
|
||||||
|
ok(N.safePath('/%2F%2Fevil.example') === '/%2F%2Fevil.example', 'an encoded // stays a path on this site');
|
||||||
|
const t2 = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: 'https://evil.example/' });
|
||||||
|
ok(N.verify(t2, { iss: 'linkspin', aud: 'iap', st }).to === '/', 'a token carrying an off-site path lands on /');
|
||||||
|
|
||||||
|
// ---- bots ----
|
||||||
|
const R = (url, cookie, ua, extra) => ({ method: 'GET', url, headers: Object.assign({ cookie: cookie || '', 'user-agent': ua === undefined ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130 Safari/537.36' : ua }, extra || {}) });
|
||||||
|
ok(N.isBot(R('/', '', 'Googlebot/2.1')) && N.isBot(R('/', '', 'facebookexternalhit/1.1')) && N.isBot(R('/', '', '')) && N.isBot(R('/', '', 'Mozilla/5.0 HeadlessChrome/120')) && !N.isBot(R('/')), 'bots, previews, headless and empty agents are bots; a browser is not');
|
||||||
|
|
||||||
|
// ---- the handler ----
|
||||||
|
const call = async req => { let code = 0, h = {}, body = ''; const res = { writeHead: (c, hh) => { code = c; h = hh || {}; }, end: b => { body = b || ''; } };
|
||||||
|
const handled = await N.handle(req, res, new URL(req.url, 'http://x')); const set = [].concat(h['Set-Cookie'] || []); return { handled, code, loc: h.Location, set, body }; };
|
||||||
|
let r = await call(R('/go/linkspin?to=/ads'));
|
||||||
|
ok(r.code === 302 && r.loc === 'https://ls.example/ads', '/go signed out: a plain link to the other site');
|
||||||
|
r = await call(R('/go/linkspin?to=//evil.example', 'sid=tok-a'));
|
||||||
|
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2F', '/go never forwards an off-site path', r.loc);
|
||||||
|
r = await call(R('/go/linkspin?to=/ads%3Fx%3D1', 'sid=tok-a'));
|
||||||
|
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2Fads%3Fx%3D1', '/go signed in: through the other site\'s /sso/start', r.loc);
|
||||||
|
r = await call(R('/sso/start?to=/my', '', 'Googlebot/2.1'));
|
||||||
|
ok(r.loc === '/my' && !r.set.length, 'bot on /sso/start: no bounce, no cookies');
|
||||||
|
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
||||||
|
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
||||||
|
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
||||||
|
ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page');
|
||||||
|
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
||||||
|
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
||||||
|
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
||||||
|
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||||
|
r = await call(R('/sso/start?to=https://evil.example'));
|
||||||
|
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
||||||
|
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
|
||||||
|
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
||||||
|
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
||||||
|
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
||||||
|
ok(r.loc === 'https://ls.example/sso/in?none=1&to=%2Fads', 'provider, signed out: none');
|
||||||
|
r = await call(R('/sso/check?st=nothex&to=/ads', 'sid=tok-a'));
|
||||||
|
ok(r.loc.includes('none=1'), 'provider: a malformed state gets none, never a token');
|
||||||
|
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
||||||
|
const issued = new URL(r.loc).searchParams.get('t');
|
||||||
|
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
||||||
|
// receiver: a LinkSpin-issued token arriving here
|
||||||
|
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
||||||
|
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
||||||
|
ok(r.loc === '/my#buy' && r.set.includes('iap.sid=new; Path=/; HttpOnly') && signedIn.length === 1, 'receiver: valid token -> session cookie, redirect to the path');
|
||||||
|
const once = mk('a@example.com', '/my');
|
||||||
|
r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st)); r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st));
|
||||||
|
ok(signedIn.length === 2 && !r.set.some(c => c.startsWith('iap.sid=')), 'receiver: the same token twice signs in once (replay refused)');
|
||||||
|
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my'), 'nsso.st=' + crypto.randomBytes(16).toString('hex')));
|
||||||
|
ok(signedIn.length === 2 && r.loc === '/my', 'receiver: a token pushed into another browser (login CSRF) is refused');
|
||||||
|
r = await call(R('/sso/in?t=' + issued, 'nsso.st=' + st));
|
||||||
|
ok(signedIn.length === 2, 'receiver: a token minted FOR the other site is refused here');
|
||||||
|
r = await call(R('/sso/in?t=' + mk('new@example.com', '/my'), 'nsso.st=' + st));
|
||||||
|
ok(signedIn.length === 2 && r.loc === '/my' && r.set.some(c => /^nsso\.hint=new%40example\.com;.*HttpOnly/.test(c)), 'receiver: not a member here yet -> normal sign-in with the email kept for the form, nothing created');
|
||||||
|
r = await call(R('/sso/in?none=1&to=https://evil.example', 'nsso.st=' + st));
|
||||||
|
ok(r.loc === '/my' && r.set.some(c => /^nsso\.st=;/.test(c)), 'receiver: none -> the sign-in page, never an off-site path');
|
||||||
|
r = await call(R('/api/sso/status', 'nsso.hint=new%40example.com; nsso.tried=1'));
|
||||||
|
let j = JSON.parse(r.body); ok(j.hint === 'new@example.com' && j.check === false && r.set.some(c => /^nsso\.hint=;/.test(c)), '/api/sso/status hands the hint over once and clears it');
|
||||||
|
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === true && j.peer === 'LinkSpin', '/api/sso/status: signed out, fresh browser -> check');
|
||||||
|
j = JSON.parse((await call(R('/api/sso/status', 'sid=tok-a'))).body); ok(j.check === false, '/api/sso/status: signed in -> no check');
|
||||||
|
j = JSON.parse((await call(R('/api/sso/status', '', 'Googlebot/2.1'))).body); ok(j.check === false, '/api/sso/status: bot -> no check');
|
||||||
|
process.env.NETWORK_SSO_SECRET = '';
|
||||||
|
r = await call(R('/go/linkspin?to=/ads', 'sid=tok-a')); ok(r.loc === 'https://ls.example/ads', 'secret not set: /go is a plain link');
|
||||||
|
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === false, 'secret not set: no silent check');
|
||||||
|
ok(N.offCookie().startsWith('nsso.off=1;') && /Max-Age=43200/.test(N.offCookie()), 'sign-out cookie pauses the silent check 12 hours');
|
||||||
|
ok(!(await call({ method: 'POST', url: '/sso/in', headers: {} })).handled, 'non-GET requests are not handled');
|
||||||
|
})().catch(e => { console.log('FAIL exception', e && e.stack || e); fails++; }).finally(() => {
|
||||||
|
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exitCode = fails ? 1 : 0;
|
||||||
|
});
|
||||||
@@ -2,15 +2,18 @@
|
|||||||
# InstantAdPay QA harness runner. From the site dir:
|
# InstantAdPay QA harness runner. From the site dir:
|
||||||
# bash qa/run.sh public # live public pages only (no local server)
|
# bash qa/run.sh public # live public pages only (no local server)
|
||||||
# bash qa/run.sh member # local copy: member + admin walk
|
# bash qa/run.sh member # local copy: member + admin walk
|
||||||
|
# bash qa/run.sh sso # network sign-in InstantAdPay <-> LinkSpin: unit + both servers end to end (NSSO_PEER_DIR = the other repo's site dir if not side by side; also runs in member)
|
||||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||||
# bash qa/run.sh all # public + member + earn
|
# bash qa/run.sh all # public + member + earn
|
||||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
|
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
|
||||||
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
|
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
|
||||||
|
# bash qa/run.sh netconv # conversion linkage: InstantAdPay's joins, wallets, purchases counted once, own account left out, window, aged hits, two copies racing, one Reports list, the landing tag on network links
|
||||||
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
|
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
|
||||||
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
|
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
|
||||||
# bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data)
|
# bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data)
|
||||||
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
|
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
|
||||||
|
# bash qa/run.sh launchweek # launch week: contest window in Central time, exclusions, minimum sales, payout once across two copies, Founder criterion + grant (fake chain + signer)
|
||||||
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
|
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, 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 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)
|
||||||
@@ -60,15 +63,26 @@ 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" = "override" ]; then
|
elif [ "$MODE" = "override" ]; then
|
||||||
node qa/override.test.cjs || status=1
|
node qa/override.test.cjs || status=1
|
||||||
|
elif [ "$MODE" = "launchweek" ]; then
|
||||||
|
node qa/launchweek.test.cjs || status=1
|
||||||
|
elif [ "$MODE" = "sso" ]; then
|
||||||
|
node qa/networksso.test.cjs || status=1
|
||||||
|
node qa/networksso.e2e.mjs || status=1
|
||||||
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; }; stop_local 8796
|
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||||
|
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||||
|
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||||
|
node qa/tank-hold.test.mjs || status=1
|
||||||
node qa/profile-policy.test.cjs || status=1
|
node qa/profile-policy.test.cjs || status=1
|
||||||
|
node qa/netconv.test.mjs || status=1
|
||||||
elif [ "$MODE" = "policy" ]; then
|
elif [ "$MODE" = "policy" ]; then
|
||||||
node qa/profile-policy.test.cjs || status=1
|
node qa/profile-policy.test.cjs || status=1
|
||||||
elif [ "$MODE" = "sponsorfollow" ]; then
|
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||||
node qa/sponsorfollow.test.cjs || status=1
|
node qa/sponsorfollow.test.cjs || status=1
|
||||||
node qa/carry-hold.test.cjs || status=1
|
node qa/carry-hold.test.cjs || status=1
|
||||||
node qa/carry-activate.test.cjs || status=1
|
node qa/carry-activate.test.cjs || status=1
|
||||||
|
elif [ "$MODE" = "hubsync" ]; then
|
||||||
|
node qa/hubsync.test.cjs || status=1 # needs a network-hub checkout with /v1/resolve {id}: HUB_DIR=<path>
|
||||||
elif [ "$MODE" = "tankhold" ]; then
|
elif [ "$MODE" = "tankhold" ]; then
|
||||||
node qa/tank-hold.test.mjs || status=1
|
node qa/tank-hold.test.mjs || status=1
|
||||||
elif [ "$MODE" = "nas" ]; then
|
elif [ "$MODE" = "nas" ]; then
|
||||||
@@ -79,6 +93,8 @@ elif [ "$MODE" = "loginqueue" ]; then
|
|||||||
node qa/loginqueue.e2e.mjs || status=1
|
node qa/loginqueue.e2e.mjs || status=1
|
||||||
elif [ "$MODE" = "convpixel" ]; then
|
elif [ "$MODE" = "convpixel" ]; then
|
||||||
node qa/convpixel.test.mjs || status=1
|
node qa/convpixel.test.mjs || status=1
|
||||||
|
elif [ "$MODE" = "netconv" ]; then
|
||||||
|
node qa/netconv.test.mjs || status=1
|
||||||
elif [ "$MODE" = "lsid" ]; then
|
elif [ "$MODE" = "lsid" ]; then
|
||||||
node qa/lsid-pixel.test.mjs || status=1
|
node qa/lsid-pixel.test.mjs || status=1
|
||||||
elif [ "$MODE" = "kb" ]; then
|
elif [ "$MODE" = "kb" ]; then
|
||||||
@@ -88,6 +104,7 @@ elif [ "$MODE" = "earn" ]; then
|
|||||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
||||||
else
|
else
|
||||||
node qa/walk.mjs public || status=1
|
node qa/walk.mjs public || status=1
|
||||||
|
node qa/launchweek.test.cjs || status=1
|
||||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -173,6 +173,31 @@ async function network() {
|
|||||||
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
|
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
|
||||||
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
|
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
|
||||||
});
|
});
|
||||||
|
await t('Who invited you: the member names a sponsor on one platform, the other follows and agrees (2026-11-07)', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
const r = await P.tank.nameSponsor('lead@x.co', 'adopter'); assert.ok(r.ok, JSON.stringify(r));
|
||||||
|
assert.strictEqual(P.store.get('lead@x.co').by, 'invited');
|
||||||
|
const s = await settle(P, Q, ['lead@x.co', 'adopter@x.co']);
|
||||||
|
assert.strictEqual(s.moves, 1); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
|
||||||
|
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'), 'gone from the other waiting list');
|
||||||
|
assert.strictEqual(Q.store.get('lead@x.co').by, 'invited'); assert.strictEqual(Q.store.get('lead@x.co').origin, 'instantadpay');
|
||||||
|
assert.ok((await Q.tank.adopt('other@x.co', 'lead')).error, 'nobody adopts them on the other side');
|
||||||
|
assert.ok((await Q.tank.nameSponsor('lead@x.co', 'otheradopter')).error, 'the other side refuses a second name');
|
||||||
|
});
|
||||||
|
await t('Who invited you: a bound member on the other platform keeps that sponsor; reported, not moved', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
Q.bound.add('lead@x.co');
|
||||||
|
const r = await P.tank.nameSponsor('lead@x.co', 'adopter'); assert.ok(r.ok, JSON.stringify(r));
|
||||||
|
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||||
|
assert.strictEqual(d.action, 'bound'); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||||
|
});
|
||||||
|
await t('sign-up grace holds on both platforms', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
for (const X of [P, Q]) X.accounts.add('fresh@x.co', { username: 'fresh', created: Date.now() });
|
||||||
|
for (const X of [P, Q]) assert.ok(/less than 24 hours/.test((await X.tank.adopt('adopter@x.co', 'fresh')).error || ''), X.name);
|
||||||
|
assert.strictEqual(await spOf(P, 'fresh@x.co'), null); assert.strictEqual(await spOf(Q, 'fresh@x.co'), null);
|
||||||
|
});
|
||||||
|
|
||||||
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
|
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
|
||||||
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
await P.tank.adopt('adopter@x.co', 'lead');
|
await P.tank.adopt('adopter@x.co', 'lead');
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// Holding-tank adoption cap + BTC4Hits wording (2026-11-11). No server: the real tank.js with in-memory accounts, a fake
|
||||||
|
// chain and a capturing mailer/messages, on a throwaway dir. node qa/tank-cap.test.mjs
|
||||||
|
// Marty: an adopter may hold up to 10 people from the tank at one time (not yet switched on payouts), as a setting;
|
||||||
|
// a BTC4Hits import is told the truth (their BTC4Hits account moved here), never "You joined LinkSpin without a sponsor".
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const require = createRequire(path.join(SITE, 'package.json'));
|
||||||
|
delete process.env.DATABASE_URL;
|
||||||
|
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x && !c ? ' ' + String(x).slice(0, 300) : '')); if (c) passes++; else fails++; };
|
||||||
|
const DAY = 86400000;
|
||||||
|
function bench(cap) {
|
||||||
|
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
|
||||||
|
const tank = require(path.join(SITE, 'tank.js'));
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankcap-'));
|
||||||
|
const by = new Map(); let n = 100; const pub = a => a ? Object.assign({}, a) : null; const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||||
|
const accounts = { add(email, o) { by.set(email, Object.assign({ email, username: null, code: 'c' + (n++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 3 * DAY, lastSeen: 0, joinedVia: 'carried', joinedRef: 'network' }, o || {})); },
|
||||||
|
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); }, async byUsername(u) { return find(a => a.username === String(u || '').toLowerCase()); }, async byCode(c) { return find(a => a.code === String(c || '').toLowerCase()); },
|
||||||
|
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); }, async setSponsorRef(e, ref) { const a = by.get(e); a.sponsorRef = String(ref || ''); return { ok: true }; },
|
||||||
|
async listAll() { return [...by.values()].map(pub); }, async sponsorOf() { return null; }, _by: by };
|
||||||
|
const events = []; const mails = []; const chats = [];
|
||||||
|
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice(), getConfig: () => ({ explorer: 'https://polygonscan.com' }) },
|
||||||
|
messages: { sendChat: async (id, from, to, text) => { chats.push({ to, text }); }, lastFrom: async () => 0 },
|
||||||
|
mailer: { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } }, site: 'https://linkspin.test',
|
||||||
|
capOpen: cap === undefined ? undefined : () => cap, hooks: {} });
|
||||||
|
accounts.add('adopter@x.co', { username: 'helper', memberId: 77, address: '0x' + '1'.repeat(40), lastSeen: Date.now() - 3600000, joinedVia: null, joinedRef: null });
|
||||||
|
events.push({ type: 'Purchase', buyerId: 77, priceCents: 2500, block: 1 });
|
||||||
|
return { tank, accounts, mails, chats };
|
||||||
|
}
|
||||||
|
{ // default cap 10, measured as people held who have not switched on payouts
|
||||||
|
const B = bench(); const { tank, accounts, mails, chats } = B;
|
||||||
|
for (let i = 0; i < 12; i++) accounts.add('m' + i + '@b4h.test', { joinedRef: i < 6 ? 'btc4hits' : 'network' });
|
||||||
|
ok(tank.capOpen() === 10, 'default cap is 10');
|
||||||
|
let okCount = 0; for (let i = 0; i < 10; i++) { const r = await tank.adopt('adopter@x.co', 'm' + i + '@b4h.test'); if (r.ok) okCount++; else console.log(' adopt ' + i + ': ' + r.error); }
|
||||||
|
ok(okCount === 10, 'adopts 10 in a row');
|
||||||
|
const r11 = await tank.adopt('adopter@x.co', 'm10@b4h.test');
|
||||||
|
ok(r11.error && /helping 10 people/.test(r11.error) && /10 at one time is the most/.test(r11.error) && !/—/.test(r11.error), 'the 11th is refused with a clear message', JSON.stringify(r11));
|
||||||
|
const v = await tank.view('adopter@x.co'); ok(v.cap === 10 && v.eligible === false && /10 at one time/.test(v.reason), 'tank view shows cap 10 and the reason');
|
||||||
|
accounts._by.get('m3@b4h.test').memberId = 901; // one of them switched on payouts: the slot frees at once
|
||||||
|
const r11b = await tank.adopt('adopter@x.co', 'm10@b4h.test'); ok(r11b.ok, 'a held member switching on payouts frees a slot right away', JSON.stringify(r11b));
|
||||||
|
ok((await tank.adopt('adopter@x.co', 'm11@b4h.test')).error, 'and the cap holds again at 10 not yet switched on');
|
||||||
|
// wording
|
||||||
|
const imp = mails.filter(m => m.to === 'm0@b4h.test'); const reg = mails.filter(m => m.to === 'm7@b4h.test');
|
||||||
|
ok(imp.length === 1 && reg.length === 1, 'exactly one email to each adoptee', JSON.stringify(mails.map(m => m.to)));
|
||||||
|
ok(/BTC4Hits has moved to LinkSpin, and your BTC4Hits account came with you/.test(imp[0].text) && /\/from\/btc4hits/.test(imp[0].text) && !/You joined LinkSpin/.test(imp[0].text), 'BTC4Hits import: email says the account moved, points to /from/btc4hits', imp[0].text);
|
||||||
|
ok(/Your BTC4Hits account moved to LinkSpin without a sponsor/.test((chats.find(c => c.to === 'm0@b4h.test') || {}).text || ''), 'BTC4Hits import: the default first chat reads right too');
|
||||||
|
ok(/^You joined LinkSpin without a sponsor/.test(reg[0].text) && /\/my#messages/.test(reg[0].text), 'ordinary tank member keeps the old wording');
|
||||||
|
ok(imp[0].subject === '@helper is now your sponsor on LinkSpin', 'subject unchanged', imp[0].subject);
|
||||||
|
ok(!mails.some(m => /—/.test(m.text + m.subject)), 'no em dash in any adoption email');
|
||||||
|
ok(!mails.some(m => m.to === 'adopter@x.co'), 'no email to the adopter on a hand adoption');
|
||||||
|
}
|
||||||
|
{ // the setting
|
||||||
|
const B = bench(3); const { tank, accounts } = B;
|
||||||
|
for (let i = 0; i < 4; i++) accounts.add('s' + i + '@b4h.test');
|
||||||
|
for (let i = 0; i < 3; i++) await tank.adopt('adopter@x.co', 's' + i + '@b4h.test');
|
||||||
|
const r = await tank.adopt('adopter@x.co', 's3@b4h.test'); ok(r.error && /3 at one time/.test(r.error), 'tankAdoptCap setting is respected (3)', JSON.stringify(r));
|
||||||
|
const B2 = bench('junk'); ok(B2.tank.capOpen() === 10, 'a bad setting falls back to 10');
|
||||||
|
}
|
||||||
|
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
|
||||||
@@ -146,6 +146,8 @@ async function partA() {
|
|||||||
const f4b = await accounts.byEmail('free4@x.co');
|
const f4b = await accounts.byEmail('free4@x.co');
|
||||||
ok(f4b.memberId > 0 && sends.slice(n0).every(s => s.sponsorId === 11), 'retried on a later tick and switched on under A (#11), never #1', JSON.stringify(sends.slice(n0)));
|
ok(f4b.memberId > 0 && sends.slice(n0).every(s => s.sponsorId === 11), 'retried on a later tick and switched on under A (#11), never #1', JSON.stringify(sends.slice(n0)));
|
||||||
ok(chats.some(c => c.to === 'free4@x.co' && /Your LinkSpin payouts are now on under @a/.test(c.text)), 'follow-up chat once the retried activation lands');
|
ok(chats.some(c => c.to === 'free4@x.co' && /Your LinkSpin payouts are now on under @a/.test(c.text)), 'follow-up chat once the retried activation lands');
|
||||||
|
// since 2026-11-11 the cap is people held at one time who have not switched on payouts (default 10): fill A up by hand
|
||||||
|
for (let i = 0; i < tank.capOpen(); i++) { accounts.add('fill' + i + '@x.co'); await tank.adopt('a@x.co', 'fill' + i + '@x.co'); }
|
||||||
// A full (2 open), B + C stale: nobody eligible -> keep holding, one admin alert
|
// A full (2 open), B + C stale: nobody eligible -> keep holding, one admin alert
|
||||||
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
|
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
|
||||||
accounts.add('free5@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
|
accounts.add('free5@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
|
||||||
@@ -190,12 +192,157 @@ async function partA() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------------- Part B ----------------
|
// ---------------- Part B ----------------
|
||||||
|
// ---------------- Sign-up grace + "Who invited you?" (Marty approved 2026-11-07) ----------------
|
||||||
|
async function partGrace() {
|
||||||
|
console.log('-- Sign-up grace + Who invited you: tank.js with a mocked clock');
|
||||||
|
const M = 60000;
|
||||||
|
{ // hand adoption: blocked for 24 hours from created, open after, old members untouched
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('ad@x.co', 11);
|
||||||
|
accounts.add('new@x.co', { created: t0 - H }); accounts.add('old@x.co');
|
||||||
|
const w = await tank.waiting(); const row = w.find(x => x.email === 'new@x.co');
|
||||||
|
ok(row && row.opensAt === t0 + 23 * H, 'waiting(): new sign-up carries opensAt = created + 24 h', JSON.stringify(row));
|
||||||
|
ok(w.find(x => x.email === 'old@x.co').opensAt === 0, 'waiting(): an old account is open now');
|
||||||
|
ok(w[w.length - 1].email === 'new@x.co', 'waiting(): grace members sort after the open ones');
|
||||||
|
ok((await tank.adoptable()).every(x => x.email !== 'new@x.co'), 'adoptable() leaves out grace members (Overview note, weekly email)');
|
||||||
|
const r = await tank.adopt('ad@x.co', 'new', 'hi');
|
||||||
|
ok(r.error && /less than 24 hours/.test(r.error) && /23 h 0 min/.test(r.error), 'grace blocks a hand adoption with a plain message', JSON.stringify(r));
|
||||||
|
ok(!(await accounts.byEmail('new@x.co')).sponsorRef, '...and writes no sponsor');
|
||||||
|
ok(!B.mails.length && !B.chats.length, '...and tells nobody');
|
||||||
|
env.now = t0 + 23 * H - M;
|
||||||
|
ok((await tank.adopt('ad@x.co', 'new', 'hi')).error, 'still blocked one minute before it opens');
|
||||||
|
env.now = t0 + 23 * H + M;
|
||||||
|
const r2 = await tank.adopt('ad@x.co', 'new', 'hi');
|
||||||
|
ok(r2.ok, 'opens after 24 hours', JSON.stringify(r2));
|
||||||
|
const r3 = await tank.adopt('ad@x.co', 'old', 'hi');
|
||||||
|
ok(r3.ok, 'an old account is adoptable at once (back in the tank later = no grace)', JSON.stringify(r3));
|
||||||
|
}
|
||||||
|
{ // wallet in the first hour: hand adoption opens at 24 h, the safety net keeps its own clock
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('ad@x.co', 11); B.buyer('ad2@x.co', 12);
|
||||||
|
accounts.add('w@x.co', { created: t0 });
|
||||||
|
env.now = t0 + H; accounts._by.get('w@x.co').address = addr(); accounts._by.get('w@x.co').lastSeen = env.now;
|
||||||
|
const t1 = await tank.readyTick();
|
||||||
|
ok(t1.fresh.length === 0, 'wallet in the first hour: no "adopt them" notice during the grace', JSON.stringify(t1.fresh));
|
||||||
|
const h = await tank.holdFor(await accounts.byEmail('w@x.co'));
|
||||||
|
ok(h.hold.since === t0 + H && h.hold.until === t0 + 25 * H, 'the hold clock runs from the wallet link, not stretched by the grace', JSON.stringify(h.hold));
|
||||||
|
env.now = t0 + 23 * H; ok((await tank.readyTick()).fresh.length === 0, 'still no notice at 23 hours');
|
||||||
|
ok((await tank.adopt('ad@x.co', 'w', 'hi')).error, 'hand adoption refused at 23 hours');
|
||||||
|
env.now = t0 + 24 * H + M; for (const em of ['ad@x.co', 'ad2@x.co']) accounts._by.get(em).lastSeen = env.now;
|
||||||
|
const t2 = await tank.readyTick();
|
||||||
|
ok(t2.fresh.length === 1 && t2.fresh[0].until === t0 + 25 * H && !t2.assigned.length, 'grace over: notice once, with the real end of the hold', JSON.stringify(t2.fresh));
|
||||||
|
ok(tank.leftText(t2.fresh[0].until - env.now) === '59 min', 'the notice text can say the time really left', tank.leftText(t2.fresh[0].until - env.now));
|
||||||
|
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
|
||||||
|
env.now = t0 + 25 * H - 10 * M;
|
||||||
|
const t3 = await tank.readyTick();
|
||||||
|
ok(t3.assigned.length === 1 && t3.assigned[0].adoptee === 'w@x.co', 'the rotation takes them inside 24 hours of the wallet link', JSON.stringify(t3.assigned));
|
||||||
|
}
|
||||||
|
{ // wallet in the first minutes: the rotation fires just before the grace ends, no notice ever goes out
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('ad@x.co', 11);
|
||||||
|
accounts.add('fast@x.co', { created: t0, address: addr() });
|
||||||
|
env.now = t0 + 5 * M; ok((await tank.readyTick()).fresh.length === 0, 'wallet in minute 5: no notice');
|
||||||
|
env.now = t0 + 24 * H - 5 * M; accounts._by.get('ad@x.co').lastSeen = env.now;
|
||||||
|
const t = await tank.readyTick();
|
||||||
|
ok(t.assigned.length === 1 && t.fresh.length === 0, 'auto path unaffected: assigned inside the grace (24 h from the wallet link), no adopt notice', JSON.stringify({ a: t.assigned, f: t.fresh }));
|
||||||
|
ok((await accounts.byEmail('fast@x.co')).sponsorRef === 'ad', 'the safety net wrote the sponsor');
|
||||||
|
}
|
||||||
|
{ // grace ends in the last tick of the hold: the safety net takes them, nobody is told to adopt someone already gone
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('ad@x.co', 11);
|
||||||
|
accounts.add('mid@x.co', { created: t0 });
|
||||||
|
env.now = t0 + 10 * M; accounts._by.get('mid@x.co').address = addr(); await tank.readyTick();
|
||||||
|
env.now = t0 + 24 * H + M; accounts._by.get('ad@x.co').lastSeen = env.now; // 9 minutes of hold left: inside the last tick
|
||||||
|
const t = await tank.readyTick();
|
||||||
|
ok(t.assigned.length === 1 && t.fresh.length === 0, 'no notice for someone the rotation takes in the same tick', JSON.stringify({ a: t.assigned, f: t.fresh }));
|
||||||
|
}
|
||||||
|
{ // the arrivals post: announced when the grace ends
|
||||||
|
const B = bench(); const { tank, env } = B; const t0 = env.now;
|
||||||
|
const list = [{ email: 'a', joined: t0 - 24 * H - 5 * M }, { email: 'b', joined: t0 - 24 * H - 20 * M }, { email: 'c', joined: t0 - H }];
|
||||||
|
ok(tank.openedSince(list, t0 - 15 * M).map(x => x.email).join() === 'a', 'openedSince: only people whose grace ended since the last check');
|
||||||
|
}
|
||||||
|
{ // Who invited you: every refusal, nothing written
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('boss@x.co', 21);
|
||||||
|
accounts.add('m@x.co', { username: 'mm1', created: t0 });
|
||||||
|
accounts.add('kid@x.co', { username: 'kid', sponsorRef: 'mm1' }); // joined under m: a loop
|
||||||
|
accounts.add('free@x.co', { username: 'free' }); // no payouts, nobody above them
|
||||||
|
accounts.add('under@x.co', { username: 'under', sponsorRef: 'boss' }); // no payouts, but boss above them
|
||||||
|
accounts.add('has@x.co', { username: 'hassp', sponsorRef: 'boss' });
|
||||||
|
accounts.add('bound@x.co', { username: 'bound1', memberId: 55 });
|
||||||
|
const say = async (e, who) => { const r = await tank.nameSponsor(e, who); return r.error || ''; };
|
||||||
|
ok(/Type the username/.test(await say('m@x.co', ' ')), 'refused: empty');
|
||||||
|
ok(/That is you/.test(await say('m@x.co', '@MM1')), 'refused: self (any case, leading @)');
|
||||||
|
ok(/No member here/.test(await say('m@x.co', 'nosuchname')), 'refused: unknown username');
|
||||||
|
ok(/No member here/.test(await say('m@x.co', 'bad name!')), 'refused: not a username');
|
||||||
|
ok(/already have a sponsor/.test(await say('has@x.co', 'boss')), 'refused: already sponsored');
|
||||||
|
ok(/locked on the contract/.test(await say('bound@x.co', 'boss')), 'refused: member id');
|
||||||
|
ok(/in your own line/.test(await say('m@x.co', 'kid')), 'refused: chain loop (inDownlineOf)');
|
||||||
|
ok(/nobody above them/.test(await say('m@x.co', 'free')), 'refused: nobody on the contract in that line (would fall to the company)');
|
||||||
|
B.blocked.add(21);
|
||||||
|
ok(/cannot take new members/.test(await say('m@x.co', 'boss')), 'refused: no-payout chain');
|
||||||
|
B.blocked.delete(21);
|
||||||
|
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'no refusal wrote a sponsor or sent a notice');
|
||||||
|
const c = await tank.nameSponsor('m@x.co', 'boss', { check: true });
|
||||||
|
ok(c.ok && c.name === '@boss' && !(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'check mode validates and writes nothing', JSON.stringify(c));
|
||||||
|
ok((await tank.nameSponsor('m@x.co', 'under', { check: true })).ok, 'a sponsor with no payouts but someone above them on the contract is allowed');
|
||||||
|
B.net['m2@x.co'] = { sponsorEmail: 'boss@x.co', via: 'email' };
|
||||||
|
accounts.add('m2@x.co', { username: 'mm2' });
|
||||||
|
const al = await tank.nameSponsor('m2@x.co', 'under');
|
||||||
|
ok(al.error && al.aligned && (await accounts.byEmail('m2@x.co')).sponsorRef === 'boss', 'the sponsor the network already knows comes first', JSON.stringify(al));
|
||||||
|
}
|
||||||
|
{ // Who invited you: success
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
|
||||||
|
accounts.add('m@x.co', { username: 'mm1', created: t0 });
|
||||||
|
const m0 = await accounts.byEmail('m@x.co');
|
||||||
|
ok(tank.inviteAsk(m0) && tank.inviteAsk(m0).dismissed === false, 'inviteAsk: the card shows for a tank member');
|
||||||
|
ok(tank.inviteAsk(await accounts.byEmail('boss@x.co')) === null, 'inviteAsk: no card for a member with a sponsor line / member id');
|
||||||
|
tank.dismissInvite('m@x.co');
|
||||||
|
ok(tank.inviteAsk(m0).dismissed === true, 'Nobody invited me: card dismissed');
|
||||||
|
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && (await tank.waiting()).some(w => w.email === 'm@x.co'), '...nothing else changes: still in the tank');
|
||||||
|
const r = await tank.nameSponsor('m@x.co', '@Boss');
|
||||||
|
ok(r.ok && r.name === '@boss', 'prompt success', JSON.stringify(r));
|
||||||
|
const a = await accounts.byEmail('m@x.co');
|
||||||
|
ok(a.sponsorRef === 'boss', 'sponsor written');
|
||||||
|
ok((await tank.holdFor(a)) === null && tank.inviteAsk(a) === null, 'hold gone, card gone');
|
||||||
|
ok(!(await tank.waiting()).some(w => w.email === 'm@x.co'), 'out of the waiting list');
|
||||||
|
ok(B.mails.length === 1 && B.mails[0].to === 'boss@x.co' && /new referral/.test(B.mails[0].subject), 'the named sponsor gets the notice, nobody else', JSON.stringify(B.mails.map(x => x.to)));
|
||||||
|
ok(!B.chats.length, 'no chat written in the sponsor\'s name');
|
||||||
|
const v = await tank.adminView(); const rec = v.adoptions.find(x => x.adoptee === 'm@x.co');
|
||||||
|
ok(rec && rec.status === 'invited' && rec.adopter === 'boss@x.co', 'admin record: status invited');
|
||||||
|
ok((await tank.summaryFor('m@x.co')) === null, 'not an adoption: nothing counts toward the two, nothing open on the other site');
|
||||||
|
const again = await tank.nameSponsor('m@x.co', 'ad');
|
||||||
|
ok(/already have a sponsor/.test(again.error || '') && (await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'a second name is refused');
|
||||||
|
env.now = t0 + 8 * 86400000; await tank.sweep();
|
||||||
|
ok((await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'no 7-day window: still theirs after a week');
|
||||||
|
}
|
||||||
|
{ // a ready member names someone: the hold record clears the way an adoption does, no auto-assign
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
|
||||||
|
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
|
||||||
|
accounts.add('r@x.co', { username: 'rr1', created: t0, address: addr() });
|
||||||
|
await tank.readyTick();
|
||||||
|
ok(tank.readyRec('r@x.co'), 'setup: on the 24-hour clock');
|
||||||
|
const r = await tank.nameSponsor('r@x.co', 'boss');
|
||||||
|
ok(r.ok && !tank.readyRec('r@x.co'), 'the hold record clears', JSON.stringify(r));
|
||||||
|
env.now = t0 + 24 * H;
|
||||||
|
for (const em of ['boss@x.co', 'ad@x.co']) accounts._by.get(em).lastSeen = env.now;
|
||||||
|
ok(!(await tank.readyTick()).assigned.length && (await accounts.byEmail('r@x.co')).sponsorRef === 'boss', 'the rotation leaves them alone');
|
||||||
|
await sleep(40);
|
||||||
|
ok(B.sends.length === 1 && B.sends[0].sponsorId === 21, 'wallet linked: the engine switches payouts on under the named sponsor, same as an adoption', JSON.stringify(B.sends));
|
||||||
|
const B2 = bench(); B2.buyer('boss@x.co', 21); const w = addr(); B2.accounts.add('c@x.co', { username: 'cc1', address: w }); B2.onchain.set(w, 77);
|
||||||
|
ok(/locked on the contract/.test((await B2.tank.nameSponsor('c@x.co', 'boss')).error || ''), 'refused: wallet already on the contract, member number not saved yet');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function partB() {
|
async function partB() {
|
||||||
console.log('-- Part B: local copy + mock InstantAdPay');
|
console.log('-- Part B: local copy + mock InstantAdPay');
|
||||||
const PORT = Number(process.env.TANKHOLD_PORT || 8803), IAPPORT = PORT + 1;
|
const PORT = Number(process.env.TANKHOLD_PORT || 8803), IAPPORT = PORT + 1;
|
||||||
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN_PW = 'localtest-th';
|
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN_PW = 'localtest-th';
|
||||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
const SECRET = crypto.randomBytes(24).toString('hex'); // throwaway
|
const SECRET = crypto.randomBytes(24).toString('hex'); // throwaway
|
||||||
|
{ const a = { email: 'qa-sponsor@example.com', pass: null, sponsorRef: '', code: 'cqasp1', username: 'qasponsor', address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, memberId: 42 }; // a member with a contract position, for the Who invited you checks
|
||||||
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify({ v: 2, byEmail: { [a.email]: a }, byAddress: {}, byCode: { [a.code]: a.email }, joins: 0, positions: {} })); }
|
||||||
const iapRows = {}; let factsCalls = 0;
|
const iapRows = {}; let factsCalls = 0;
|
||||||
const mock = http.createServer((req, res) => { let d = ''; req.on('data', c => d += c); req.on('end', () => {
|
const mock = http.createServer((req, res) => { let d = ''; req.on('data', c => d += c); req.on('end', () => {
|
||||||
const sig = crypto.createHmac('sha256', SECRET).update(String(req.headers['x-ls-ts'] || '') + '\n' + d).digest('hex');
|
const sig = crypto.createHmac('sha256', SECRET).update(String(req.headers['x-ls-ts'] || '') + '\n' + d).digest('hex');
|
||||||
@@ -281,6 +428,48 @@ async function partB() {
|
|||||||
ok(!st.act && st.buy && !st.hold, 'Credits: no Switch on payouts button, Buy still there, no hold box on the buy side', JSON.stringify(st));
|
ok(!st.act && st.buy && !st.hold, 'Credits: no Switch on payouts button, Buy still there, no hold box on the buy side', JSON.stringify(st));
|
||||||
try { fs.mkdirSync(path.join(SITE, 'qa/out'), { recursive: true }); await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-credits.png'), fullPage: true }); } catch (e) {}
|
try { fs.mkdirSync(path.join(SITE, 'qa/out'), { recursive: true }); await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-credits.png'), fullPage: true }); } catch (e) {}
|
||||||
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
|
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
|
||||||
|
{ // Who invited you + the sign-up grace, on the real pages (2026-11-07)
|
||||||
|
const nc = await signIn('qa-new@example.com'); await req('POST', '/api/my/profile', { cookie: nc, body: { username: 'qanewone' } });
|
||||||
|
const m0 = (await req('GET', '/api/me', { cookie: nc })).json;
|
||||||
|
ok(m0 && m0.inviteAsk && m0.inviteAsk.dismissed === false, '/api/me: inviteAsk for a tank member', JSON.stringify(m0 && m0.inviteAsk));
|
||||||
|
const sc = await signIn('qa-sponsor@example.com');
|
||||||
|
const tv = (await req('GET', '/api/my/tank', { cookie: sc })).json; const row6 = tv && tv.waiting.find(w => w.email === 'qa-new@example.com');
|
||||||
|
ok(row6 && row6.opensAt > Date.now(), '/api/my/tank: a new sign-up is listed with opensAt', JSON.stringify(row6));
|
||||||
|
const bad = await req('POST', '/api/my/tank/invited', { cookie: nc, body: { who: 'nosuchname' } });
|
||||||
|
ok(bad.status === 400 && /No member here/.test(bad.json.error), 'POST invited: unknown username refused', JSON.stringify(bad.json));
|
||||||
|
const self = await req('POST', '/api/my/tank/invited', { cookie: nc, body: { who: 'qanewone' } });
|
||||||
|
ok(self.status === 400 && /That is you/.test(self.json.error), 'POST invited: self refused', JSON.stringify(self.json));
|
||||||
|
ok((await req('POST', '/api/my/tank/invited', { body: { who: 'qasponsor' } })).status === 401, 'POST invited: signed out refused');
|
||||||
|
const c2 = await browser.newContext({ viewport: { width: 390, height: 900 } });
|
||||||
|
await c2.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} });
|
||||||
|
await c2.addCookies(nc.split('; ').filter(Boolean).map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
||||||
|
const pg = await c2.newPage(); pg.on('pageerror', e => errs.push(e.message));
|
||||||
|
await pg.goto(BASE + '/links', { waitUntil: 'load' }); await pg.waitForSelector('#crInvite', { timeout: 15000 }).catch(() => {});
|
||||||
|
const has = sel => pg.evaluate(s => !!document.querySelector(s), sel);
|
||||||
|
ok(await has('#inviteWho'), 'Control Room (/links): Who invited you box shows');
|
||||||
|
const over = await pg.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||||
|
ok(over <= 0, 'no sideways scroll at phone width', String(over));
|
||||||
|
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-invite-card.png') }).catch(() => {});
|
||||||
|
await pg.fill('#inviteWho', 'nosuchname'); await pg.click('#inviteGo'); await pg.waitForTimeout(700);
|
||||||
|
ok(/No member here/.test(await pg.textContent('#inviteMsg')), 'box: the refusal shows in the box');
|
||||||
|
await pg.click('#inviteNo'); await pg.waitForTimeout(500);
|
||||||
|
ok(!(await has('#crInvite')), 'Nobody invited me: gone from the screen');
|
||||||
|
await pg.goto(BASE + '/links', { waitUntil: 'load' }); await pg.waitForTimeout(2500);
|
||||||
|
ok(!(await has('#crInvite')), 'stays gone on the next screen');
|
||||||
|
await pg.goto(BASE + '/tools', { waitUntil: 'load' }); await pg.waitForSelector('#inviteBack', { timeout: 15000 }).catch(() => {});
|
||||||
|
ok(await has('#inviteBack'), '/tools: the small link is there');
|
||||||
|
await pg.click('#inviteBack'); await pg.fill('#inviteWho', '@qasponsor'); await pg.click('#inviteGo'); await pg.waitForSelector('#dlgNo', { timeout: 5000 });
|
||||||
|
await pg.click('#dlgNo'); await pg.waitForTimeout(400);
|
||||||
|
ok(!(await req('GET', '/api/me', { cookie: nc })).json.sponsorName, 'box: Not them writes nothing');
|
||||||
|
await pg.click('#inviteGo'); await pg.waitForSelector('#dlgOk', { timeout: 5000 }); await pg.click('#dlgOk'); await pg.waitForTimeout(3000);
|
||||||
|
const m1 = (await req('GET', '/api/me', { cookie: nc })).json;
|
||||||
|
ok(m1 && m1.sponsorName === '@qasponsor' && !m1.inviteAsk, 'box: yes sets the sponsor, the box is gone', JSON.stringify({ n: m1 && m1.sponsorName, a: m1 && m1.inviteAsk }));
|
||||||
|
ok(!(await has('#crInvite')), 'box: gone after the reload');
|
||||||
|
const adm6 = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json;
|
||||||
|
ok(adm6.adoptions.some(a => a.adoptee === 'qa-new@example.com' && a.status === 'invited'), 'admin tank: the invited record shows');
|
||||||
|
await c2.close();
|
||||||
|
ok(!errs.length, 'no page errors (Who invited you)', errs.join(' | ').slice(0, 200));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (browser) await browser.close().catch(() => {});
|
if (browser) await browser.close().catch(() => {});
|
||||||
@@ -291,6 +480,7 @@ async function partB() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await partA();
|
await partA();
|
||||||
|
await partGrace();
|
||||||
if (process.argv[2] !== 'unit') await partB();
|
if (process.argv[2] !== 'unit') await partB();
|
||||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
|
||||||
process.exit(fails ? 1 : 0);
|
process.exit(fails ? 1 : 0);
|
||||||
|
|||||||
+1
-1
@@ -66,7 +66,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 LinkSpin Telegram group.</p>';
|
h += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the LinkSpin Telegram group.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261101t"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261113nl"></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 };
|
||||||
|
|||||||
+34
-12
@@ -13,6 +13,7 @@ const crypto = require('crypto');
|
|||||||
|
|
||||||
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
|
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
|
||||||
let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk=
|
let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk=
|
||||||
|
let IS_NETWORK = () => false, GOAL_ROWS = () => []; // 2026-11-07: a page on a network host always gets the click id (InstantAdPay reports joins, wallets, purchases against it); goal conversions as rotator-shaped rows for per-link counts
|
||||||
const DAY = 86400000;
|
const DAY = 86400000;
|
||||||
const J = {
|
const J = {
|
||||||
db: null,
|
db: null,
|
||||||
@@ -20,7 +21,8 @@ const J = {
|
|||||||
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
|
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
|
||||||
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
|
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
|
||||||
};
|
};
|
||||||
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; J.load(); }
|
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; if (opts.isNetworkHost) IS_NETWORK = opts.isNetworkHost; if (opts.goalRows) GOAL_ROWS = opts.goalRows; J.load(); }
|
||||||
|
const convOf = (rid) => J.db.conv.filter(c => c.r === rid).concat(GOAL_ROWS().filter(c => c.r === rid)); // a link's conversions: site and network events, and goals
|
||||||
const norm = e => String(e || '').trim().toLowerCase();
|
const norm = e => String(e || '').trim().toLowerCase();
|
||||||
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
|
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
|
||||||
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
|
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
|
||||||
@@ -83,7 +85,7 @@ function pub(r) {
|
|||||||
const since7 = Date.now() - 7 * DAY;
|
const since7 = Date.now() - 7 * DAY;
|
||||||
const perDest = {};
|
const perDest = {};
|
||||||
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
|
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
|
||||||
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
|
const conv = convOf(r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
|
||||||
const since30 = Date.now() - 30 * DAY;
|
const since30 = Date.now() - 30 * DAY;
|
||||||
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
|
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
|
||||||
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '',
|
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '',
|
||||||
@@ -128,13 +130,18 @@ async function update(owner, id, body) {
|
|||||||
J.save(); return { ok: true, rotation: pub(r) };
|
J.save(); return { ok: true, rotation: pub(r) };
|
||||||
}
|
}
|
||||||
async function remove(owner, id) { const n = J.db.rotations.length; J.db.rotations = J.db.rotations.filter(r => !(r.id === Number(id) && r.owner === norm(owner))); J.save(); return n !== J.db.rotations.length ? { ok: true } : { error: 'No such rotation.' }; }
|
async function remove(owner, id) { const n = J.db.rotations.length; J.db.rotations = J.db.rotations.filter(r => !(r.id === Number(id) && r.owner === norm(owner))); J.save(); return n !== J.db.rotations.length ? { ok: true } : { error: 'No such rotation.' }; }
|
||||||
async function addDest(owner, id, body) {
|
// opts.max: the admin import path only (BTC4Hits rotators, 2026-11-11) may go past the 25 a member can add, up to IMPORT_MAX
|
||||||
|
const DEST_MAX = 25, IMPORT_MAX = 2000;
|
||||||
|
async function addDest(owner, id, body, opts) {
|
||||||
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
|
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
|
||||||
const url = cleanUrl(body.url); if (!url) return { error: 'Destination must be a full https:// address.' };
|
const url = cleanUrl(body.url); if (!url) return { error: 'Destination must be a full https:// address.' };
|
||||||
if (r.destinations.length >= 25) return { error: 'Up to 25 destinations per rotation.' };
|
const cap = opts && opts.max ? Math.min(IMPORT_MAX, Math.max(DEST_MAX, Math.round(Number(opts.max) || DEST_MAX))) : DEST_MAX;
|
||||||
|
if (r.destinations.length >= cap) return { error: 'Up to ' + DEST_MAX + ' destinations per rotation.' };
|
||||||
const w = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
|
const w = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
|
||||||
const d = { id: r.nextDest++, url, label: String(body.label || '').trim().slice(0, 60), weight: w, active: true, added: Date.now() };
|
const d = { id: r.nextDest++, url, label: String(body.label || '').trim().slice(0, 60), weight: w, active: true, added: Date.now() };
|
||||||
r.destinations.push(d); J.save(); return { ok: true, rotation: pub(r) };
|
r.destinations.push(d);
|
||||||
|
if (opts && opts.defer) return { ok: true, id: d.id }; // bulk import: the caller saves once at the end (rotator.json holds every click, ~18 MB; one write per destination would stall the app)
|
||||||
|
J.save(); return { ok: true, rotation: pub(r) };
|
||||||
}
|
}
|
||||||
async function updateDest(owner, id, did, body) {
|
async function updateDest(owner, id, did, body) {
|
||||||
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
|
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
|
||||||
@@ -191,19 +198,27 @@ async function resolve(code, req) {
|
|||||||
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
|
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
|
||||||
// conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets
|
// conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets
|
||||||
// ?lsclk=<this click id> for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone.
|
// ?lsclk=<this click id> for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone.
|
||||||
if (!bot && (ac || WANTS_CLICK_ID(r.owner))) { try { const t = new URL(out); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
|
if (!bot) { try { const t = new URL(out); if ((ac || WANTS_CLICK_ID(r.owner) || IS_NETWORK(t.hostname)) && !t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
|
||||||
}
|
}
|
||||||
return { url: out, dest: d, rotation: r, lsid: id };
|
return { url: out, dest: d, rotation: r, lsid: id };
|
||||||
}
|
}
|
||||||
// conversions: record an event against the click that brought the person (dedupe per click + event)
|
// conversions: record an event against the click that brought the person (dedupe per click + event)
|
||||||
// Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it
|
// Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it
|
||||||
let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; }
|
let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; }
|
||||||
|
// facts.key (netconv.js, 2026-11-07): every purchase InstantAdPay reports counts by its own key, not once per click; facts.bound =
|
||||||
|
// the click as first recorded, so an event still lands on its link after the hit aged out of the array
|
||||||
async function convert(lsid, ev, facts) {
|
async function convert(lsid, ev, facts) {
|
||||||
const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
|
const f = facts || {}; const key = f.key ? String(f.key) : ''; const id = String(lsid);
|
||||||
|
let h = J.db.hits.find(x => x.id === id);
|
||||||
|
if (!h && f.bound && f.bound.r) h = { id, r: f.bound.r, d: f.bound.d, sr: f.bound.sr };
|
||||||
|
if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
|
||||||
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
|
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
|
||||||
if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: h.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
const dup = J.db.conv.some(c => key && ev === 'purchase' ? c.key === key : (c.lsid === h.id && c.ev === ev && (ev !== 'purchase' || !c.key)));
|
||||||
|
if (!dup) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Number(f.ts) || Date.now(), value: Number(f.payout || 0) || 0, label: f.label ? String(f.label).slice(0, 40) : undefined, sr: h.sr || undefined, key: key || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
|
||||||
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
|
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
|
||||||
}
|
}
|
||||||
|
// a member's conversions as rows (Reports' one Conversions panel, netconv.unified): goals are added there, never here
|
||||||
|
function convRows(owner, since) { const ids = new Set(J.db.rotations.filter(r => r.owner === norm(owner)).map(r => r.id)); return J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); }
|
||||||
// clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports
|
// clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports
|
||||||
async function sourceCounts(owner, days) {
|
async function sourceCounts(owner, days) {
|
||||||
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
|
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
|
||||||
@@ -211,7 +226,7 @@ async function sourceCounts(owner, days) {
|
|||||||
const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 });
|
const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 });
|
||||||
for (const r of mine) if (r.sourceId) at(r.sourceId).links++;
|
for (const r of mine) if (r.sourceId) at(r.sourceId).links++;
|
||||||
for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); }
|
for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); }
|
||||||
for (const c of J.db.conv) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
|
for (const c of J.db.conv.concat(GOAL_ROWS())) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
|
||||||
for (const k in out) out[k].unique = out[k].unique.size;
|
for (const k in out) out[k].unique = out[k].unique.size;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -229,7 +244,7 @@ async function summary(owner, days) {
|
|||||||
const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); }
|
const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); }
|
||||||
const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b }));
|
const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b }));
|
||||||
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
|
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
|
||||||
const conv = J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
|
const conv = J.db.conv.concat(GOAL_ROWS()).filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
|
||||||
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
|
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
|
||||||
// traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried
|
// traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried
|
||||||
const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {};
|
const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {};
|
||||||
@@ -249,7 +264,7 @@ async function stats(owner, id) {
|
|||||||
const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; }
|
const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; }
|
||||||
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
|
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
|
||||||
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
|
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
|
||||||
const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
|
const conv = convOf(r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
|
||||||
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
|
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
|
||||||
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
|
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
|
||||||
}
|
}
|
||||||
@@ -295,6 +310,13 @@ function sweepDemos() {
|
|||||||
if (gone.size) { J.db.hits = J.db.hits.filter(h => !gone.has(h.r)); J.db.conv = J.db.conv.filter(c => !gone.has(c.r)); J.save(); }
|
if (gone.size) { J.db.hits = J.db.hits.filter(h => !gone.has(h.r)); J.db.conv = J.db.conv.filter(c => !gone.has(c.r)); J.save(); }
|
||||||
return gone.size;
|
return gone.size;
|
||||||
}
|
}
|
||||||
|
// site-wide figures for the daily snapshot (snapshot.js): the last `since` window, every owner, bots left out
|
||||||
|
function window24(since) {
|
||||||
|
const hits = J.db.hits.filter(h => h.ts >= since); const real = hits.filter(h => !h.bot);
|
||||||
|
return { links: J.db.rotations.length, created: J.db.rotations.filter(r => (r.created || 0) >= since).length,
|
||||||
|
served: real.length, unique: new Set(real.map(h => h.v)).size, bots: hits.length - real.length,
|
||||||
|
countries: new Set(real.map(h => h.c).filter(Boolean)).size };
|
||||||
|
}
|
||||||
function servedToday() {
|
function servedToday() {
|
||||||
// Central-time day, like Reports
|
// Central-time day, like Reports
|
||||||
const now = new Date(); const ct = new Date(now.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
|
const now = new Date(); const ct = new Date(now.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
|
||||||
@@ -315,5 +337,5 @@ function adminAll() {
|
|||||||
destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })),
|
destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })),
|
||||||
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
|
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
|
||||||
}
|
}
|
||||||
module.exports = { init, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
|
module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
|
||||||
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
|
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const { URL } = require('url');
|
|||||||
const chain = require('./chain');
|
const chain = require('./chain');
|
||||||
const auth = require('./auth');
|
const auth = require('./auth');
|
||||||
const accounts = require('./accounts');
|
const accounts = require('./accounts');
|
||||||
|
const networksso = require('./networksso'); // network sign-in with InstantAdPay (2026-11-12, Marty approved): see networksso.js
|
||||||
const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages
|
const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages
|
||||||
const ads = require('./ads');
|
const ads = require('./ads');
|
||||||
const mailer = require('./mailer');
|
const mailer = require('./mailer');
|
||||||
@@ -44,6 +45,7 @@ const leaderboard = require('./leaderboard');
|
|||||||
const toolkit = require('./toolkit');
|
const toolkit = require('./toolkit');
|
||||||
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
|
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
|
||||||
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
|
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
|
||||||
|
const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12)
|
||||||
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
|
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
|
||||||
let follow = null, followStore = null;
|
let follow = null, followStore = null;
|
||||||
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||||
@@ -65,6 +67,7 @@ const rotator = require('./rotator');
|
|||||||
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
|
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
|
||||||
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
|
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
|
||||||
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
|
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
|
||||||
|
const netconv = require('./netconv'); // network conversions: InstantAdPay's joins, wallets, purchases counted for the click's owner, reporting only (2026-11-07)
|
||||||
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
|
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
|
||||||
const refill = require('./refill');
|
const refill = require('./refill');
|
||||||
const refuel = require('./refuel');
|
const refuel = require('./refuel');
|
||||||
@@ -90,6 +93,7 @@ const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays',
|
|||||||
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
|
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
|
||||||
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
|
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
|
||||||
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
||||||
|
const launchweek = require('./launchweek'); // launch week (2026-11-05): Founder badge grant + the launch contest (admin-approved POL prizes)
|
||||||
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
|
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
|
||||||
|
|
||||||
const PORT = Number(process.env.PORT || 3000);
|
const PORT = Number(process.env.PORT || 3000);
|
||||||
@@ -141,6 +145,8 @@ fs.mkdirSync(DATA_DIR, { recursive: true });
|
|||||||
const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume
|
const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume
|
||||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||||
const uploadCounts = new Map(); // email:day -> uploads today
|
const uploadCounts = new Map(); // email:day -> uploads today
|
||||||
|
// the owner (ADMIN_EMAIL) and the admin portal have no daily upload cap (Marty 2026-11-08); every other member keeps 10 a day
|
||||||
|
const uploadCapHit = (who, key) => who !== 'admin' && String(who || '').toLowerCase() !== ADMIN_EMAIL && (uploadCounts.get(key) || 0) >= 10;
|
||||||
// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a
|
// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a
|
||||||
// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart)
|
// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart)
|
||||||
const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json');
|
const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json');
|
||||||
@@ -442,7 +448,7 @@ async function handleUpload(req, res, who) {
|
|||||||
if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' });
|
if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' });
|
||||||
const isVideo = ct.startsWith('video/');
|
const isVideo = ct.startsWith('video/');
|
||||||
const key = who + ':' + new Date().toISOString().slice(0, 10);
|
const key = who + ':' + new Date().toISOString().slice(0, 10);
|
||||||
if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
if (uploadCapHit(who, key)) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
||||||
let buf;
|
let buf;
|
||||||
try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); }
|
try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); }
|
||||||
catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); }
|
catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); }
|
||||||
@@ -476,6 +482,7 @@ const JOIN_ANGLES = {
|
|||||||
'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave?seg=advertiser' },
|
'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave?seg=advertiser' },
|
||||||
'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave' },
|
'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave' },
|
||||||
't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads?seg=advertiser' },
|
't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads?seg=advertiser' },
|
||||||
|
'b4h': { t: 'BTC4Hits is now LinkSpin.', d: 'Your BTC4Hits account came with you. Sign in with the same email; an active rotator is already waiting as a LinkSpin spin link.', url: SITE_URL + '/from/btc4hits' },
|
||||||
't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads' },
|
't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads' },
|
||||||
instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' },
|
instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' },
|
||||||
adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10. Join free.' },
|
adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10. Join free.' },
|
||||||
@@ -627,6 +634,29 @@ async function boot() {
|
|||||||
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {});
|
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {});
|
||||||
if (ev && ev.type === 'Purchase') refuel.onPurchase(ev).catch(e => console.error('refuel report', e.message)); } }); // no-op while refuelStreak is off
|
if (ev && ev.type === 'Purchase') refuel.onPurchase(ev).catch(e => console.error('refuel report', e.message)); } }); // no-op while refuelStreak is off
|
||||||
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
|
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
|
||||||
|
// network sign-in (2026-11-12): a member signed in on InstantAdPay arrives here signed in, and the other way round. Member
|
||||||
|
// sessions only (the admin portal is never shared). An email that is not here yet (the 2-minute sync has not run) or is not
|
||||||
|
// let in (LS_TESTERS) gets the normal email-code sign-in with the email filled in; nothing is created by the network sign-in.
|
||||||
|
networksso.init({ self: 'linkspin', peer: 'iap', peerBase: IAP_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/ads',
|
||||||
|
wallets: { bannerline: () => String(process.env.BL_URL || 'https://new.downlinebanners.com').replace(/\/+$/, '') }, // Downline Banners by wallet (2026-11-13)
|
||||||
|
wallet: async s => { const a = await accounts.byEmail(s.email); const addr = String(s.address || (a && a.address) || '').toLowerCase(); return addr ? { address: addr, name: '' } : null; },
|
||||||
|
member: async req => { // a wallet sign-in carries the address, not the email: find the account that owns the wallet (2026-11-13)
|
||||||
|
const s = await auth.fromRequest(req); if (!s) return null;
|
||||||
|
let email = s.email || null; if (!email && s.address) { try { const a = await accounts.byAddress(s.address); if (a && a.email) email = a.email; } catch (e) {} }
|
||||||
|
return email ? Object.assign({}, s, { email }) : null; },
|
||||||
|
accept: async email => {
|
||||||
|
const a = await accounts.byEmail(email);
|
||||||
|
if (!a) return { fallback: 'no account here yet' };
|
||||||
|
if (!isTester(email, a)) return { fallback: 'not on the tester list' };
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
signIn: async email => { // the same session the email code makes (4 hours, same rights)
|
||||||
|
const a = await accounts.byEmail(email); let memberId = 0;
|
||||||
|
if (a && a.address) { try { memberId = await chain.memberIdByAccount(a.address); } catch (e) {} }
|
||||||
|
return auth.sessionCookie(await auth.mintSession({ email: a.email, address: a.address || null, memberId }));
|
||||||
|
},
|
||||||
|
landing: to => to,
|
||||||
|
signinPath: to => (to === '/' ? '/ads' : to) }); // every Control Room screen shows the sign-in itself
|
||||||
accounts.init({ dataDir: DATA_DIR });
|
accounts.init({ dataDir: DATA_DIR });
|
||||||
ads.init({ dataDir: DATA_DIR, chain });
|
ads.init({ dataDir: DATA_DIR, chain });
|
||||||
mailer.init({ dataDir: DATA_DIR });
|
mailer.init({ dataDir: DATA_DIR });
|
||||||
@@ -701,11 +731,12 @@ async function boot() {
|
|||||||
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
|
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
|
||||||
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
||||||
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
||||||
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => iapsync.touch(email));
|
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => { iapsync.touch(email); hubsync.touch(email); });
|
||||||
|
hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off
|
||||||
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||||
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||||
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
||||||
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0 });
|
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, isNetworkHost: h => networkHosts().includes(String(h || '').toLowerCase().replace(/^www\./, '')), goalRows: () => convtrack.goalRows() });
|
||||||
convtrack.init({ dataDir: DATA_DIR, rotator, bannerspin, campaignOf: id => ads.campaignById(id) });
|
convtrack.init({ dataDir: DATA_DIR, rotator, bannerspin, campaignOf: id => ads.campaignById(id) });
|
||||||
auth.onSeen((email, req) => convtrack.noteSession(email, req)); // own-click tests (2026-10-26): the soft keys a member signs in from
|
auth.onSeen((email, req) => convtrack.noteSession(email, req)); // own-click tests (2026-10-26): the soft keys a member signs in from
|
||||||
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
|
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
|
||||||
@@ -714,8 +745,9 @@ async function boot() {
|
|||||||
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
|
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
|
||||||
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
|
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
|
||||||
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
|
postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources });
|
||||||
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, withClickId: convtrack.withClickId });
|
bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: (owner, url) => { if (convtrack.goalsOf(owner).length > 0) return true; try { return networkHosts().includes(new URL(url).hostname.toLowerCase().replace(/^www\./, '')); } catch (e) { return false; } }, withClickId: convtrack.withClickId });
|
||||||
rotator.setExternalConvert((lsid, ev, facts) => bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks
|
rotator.setExternalConvert((lsid, ev, facts) => /^[ai]/.test(String(lsid)) ? netconv.fromLinkSpin(lsid, ev, facts) : bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks; ad clicks through the ledger
|
||||||
|
netconv.init({ dataDir: DATA_DIR, convtrack, rotator, bannerspin, postbacks, marks });
|
||||||
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
|
sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } });
|
||||||
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
|
zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST });
|
||||||
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { 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 ''; } } });
|
pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { 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 ''; } } });
|
||||||
@@ -724,14 +756,15 @@ async function boot() {
|
|||||||
domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)),
|
domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)),
|
||||||
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } });
|
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } });
|
||||||
zonereport.init({ dataDir: DATA_DIR });
|
zonereport.init({ dataDir: DATA_DIR });
|
||||||
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
|
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, accounts, rotator, bannerspin, zones, pages, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
|
||||||
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
|
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
|
||||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore,
|
tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore,
|
||||||
// network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never
|
// network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never
|
||||||
// bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held)
|
// bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held)
|
||||||
hooks: { network: (email, address) => networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }),
|
hooks: { network: (email, address) => networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }),
|
||||||
iapOwns: (email, o) => iapOwnsTank(email, o), bound: async a => { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) await accounts.setMemberId(a.email, id).catch(() => {}); return id; },
|
iapOwns: (email, o) => iapOwnsTank(email, o), bound: async a => { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) await accounts.setMemberId(a.email, id).catch(() => {}); return id; },
|
||||||
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
|
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
|
||||||
|
notify: (email, subject, text) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, '<p>' + String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>') + '</p>'),
|
||||||
lifted: email => tankLifted(email), claim: k => marks.claim(k), assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text) } });
|
lifted: email => tankLifted(email), claim: k => marks.claim(k), assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text) } });
|
||||||
legacy.init({ dataDir: DATA_DIR });
|
legacy.init({ dataDir: DATA_DIR });
|
||||||
traffic.init({ dataDir: DATA_DIR });
|
traffic.init({ dataDir: DATA_DIR });
|
||||||
@@ -769,6 +802,11 @@ async function boot() {
|
|||||||
override.init({ dataDir: DATA_DIR, chain, siteConfig, db, brand: 'LinkSpin', siteUrl: SITE_URL,
|
override.init({ dataDir: DATA_DIR, chain, siteConfig, db, brand: 'LinkSpin', siteUrl: SITE_URL,
|
||||||
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) { await telegramSend(sc.telegramAdminChatId, text); return true; } if (ADMIN_EMAIL && mailer.hasKey()) { await mailer.send(ADMIN_EMAIL, 'LinkSpin: level-4 override', text.replace(/<[^>]+>/g, '')); return true; } return false; } });
|
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) { await telegramSend(sc.telegramAdminChatId, text); return true; } if (ADMIN_EMAIL && mailer.hasKey()) { await mailer.send(ADMIN_EMAIL, 'LinkSpin: level-4 override', text.replace(/<[^>]+>/g, '')); return true; } return false; } });
|
||||||
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
|
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
|
||||||
|
// launch week: Founder grant from the launch moment (idempotent, every 10 minutes) + the /leaderboard contest panel; POL prizes only by the admin button
|
||||||
|
launchweek.init({ accounts, chain, marks, leaderboard, siteConfig, dataDir: DATA_DIR, adminEmail: ADMIN_EMAIL, payer: () => override.payerHandle(), txLink: h => override.polygonTx(h) });
|
||||||
|
leaderboard.setLaunchPanel(() => launchweek.panelHtml());
|
||||||
|
setTimeout(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 2 * 60 * 1000);
|
||||||
|
setInterval(() => launchweek.tick().catch(e => console.error('launchweek', e.message)), 10 * 60 * 1000);
|
||||||
if (OUTBOUND_MAIL) { // same for the lead follow-up sequence
|
if (OUTBOUND_MAIL) { // same for the lead follow-up sequence
|
||||||
setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000);
|
setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000);
|
||||||
setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000);
|
setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000);
|
||||||
@@ -802,6 +840,8 @@ function siteConfig() {
|
|||||||
telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic
|
telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic
|
||||||
telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL
|
telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL
|
||||||
spamScanAllow: spamscan.DEFAULT_ALLOW.join(', '), // link-farm scan (2026-10-30): emails never listed as candidates; Admin > Members > Link-farm list > Allow adds here
|
spamScanAllow: spamscan.DEFAULT_ALLOW.join(', '), // link-farm scan (2026-10-30): emails never listed as candidates; Admin > Members > Link-farm list > Allow adds here
|
||||||
|
founderGrant: '1', // Founder badge: '0' stops the automatic grant at the launch moment (launchweek.js); the badge is cosmetic
|
||||||
|
launchContest: '1', launchContestStart: '', launchContestEnd: '2026-11-22T00:00:00-06:00', launchContestPrizesPol: '10,6,4', launchContestMinSales: 2, launchContestMinCents: 0, launchContestExcludeEmails: '', launchContestExcludeIds: '', // launch week contest: start '' = launchAt; end is EXCLUSIVE (all of Sat Nov 21 Central); POL prizes 1st,2nd,3rd paid only by the admin button; admin + overrideHouseIds always excluded
|
||||||
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
|
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
|
||||||
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
|
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
|
||||||
carryClaimDays: '3',
|
carryClaimDays: '3',
|
||||||
@@ -815,6 +855,7 @@ function siteConfig() {
|
|||||||
memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line
|
memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line
|
||||||
noPayoutIds: '', // LinkSpin member ids differ from InstantAdPay's (IAP #25 = Jim's compromised wallet; LinkSpin #25 is a real member, cleared 2026-10-15). Positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14)
|
noPayoutIds: '', // LinkSpin member ids differ from InstantAdPay's (IAP #25 = Jim's compromised wallet; LinkSpin #25 is a real member, cleared 2026-10-15). Positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14)
|
||||||
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
|
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
|
||||||
|
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
|
||||||
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
|
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
|
||||||
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
||||||
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
||||||
@@ -872,6 +913,9 @@ function readRaw(req, maxBytes) {
|
|||||||
// on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window.
|
// on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window.
|
||||||
// the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us
|
// the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us
|
||||||
function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } }
|
function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } }
|
||||||
|
// the sites of the network a click id may travel to (the landing tag's list, 2026-11-07): this site, InstantAdPay, its share domains
|
||||||
|
const NETWORK_HOSTS = String(process.env.NETWORK_HOSTS || 'instantadpay.com,instantadpay.link,ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);
|
||||||
|
function networkHosts() { return [...new Set([String(SITE_HOST || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '')].concat(NETWORK_HOSTS))].filter(Boolean); }
|
||||||
function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); }
|
function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); }
|
||||||
// an ad click: record a click id for the campaign and append ?lsclk=<id> to the target (existing params kept, an lsclk
|
// an ad click: record a click id for the campaign and append ?lsclk=<id> to the target (existing params kept, an lsclk
|
||||||
// already there left alone). A spin-link target passes it on, so the spin-link click inherits the ad as its source.
|
// already there left alone). A spin-link target passes it on, so the spin-link click inherits the ad as its source.
|
||||||
@@ -894,10 +938,10 @@ async function adClickTarget(campOrId, url, req, extra) {
|
|||||||
return { url: out, cookie: clickCookie(id), id };
|
return { url: out, cookie: clickCookie(id), id };
|
||||||
} catch (e) { console.error('ad click id', e.message); return { url }; }
|
} catch (e) { console.error('ad click id', e.message); return { url }; }
|
||||||
}
|
}
|
||||||
function readBody(req) {
|
function readBody(req, max) { // max: a larger body for one admin route only (2026-11-11, BTC4Hits import: #297 has 834 URLs); everything else stays at 64 KB
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let d = ''; let n = 0;
|
let d = ''; let n = 0;
|
||||||
req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); reject(new Error('too big')); } d += c; });
|
req.on('data', c => { n += c.length; if (n > (max || 64 * 1024)) { req.destroy(); reject(new Error('too big')); } d += c; });
|
||||||
req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } });
|
req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } });
|
||||||
req.on('error', reject);
|
req.on('error', reject);
|
||||||
});
|
});
|
||||||
@@ -954,6 +998,17 @@ async function resolveSponsorDetailed(tok) {
|
|||||||
try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; }
|
try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; }
|
||||||
catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; }
|
catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; }
|
||||||
}
|
}
|
||||||
|
// The chain-bound sponsor of an activated member, as a resolveSponsorDetailed-shaped answer with a display name; null when the
|
||||||
|
// member is not on chain or the read fails (callers then fall back to the account's sponsor field).
|
||||||
|
async function sponsorByChain(memberId) {
|
||||||
|
const id = Number(memberId) || 0; if (id <= 0) return null;
|
||||||
|
try {
|
||||||
|
const me = await chain.member(id); const sid = Number(me && me.sponsorId) || 0; if (!sid) return null;
|
||||||
|
let name = 'member #' + sid;
|
||||||
|
try { const sp = await chain.member(sid); const a = sp && sp.account ? await accounts.byAddress(String(sp.account).toLowerCase()) : null; if (a && a.username) name = '@' + a.username; } catch (e) { /* name stays member #N */ }
|
||||||
|
return { id: sid, reason: 'ok', name, chain: true };
|
||||||
|
} catch (e) { return null; }
|
||||||
|
}
|
||||||
async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; }
|
async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; }
|
||||||
const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour)
|
const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour)
|
||||||
function sponsorBlockedAlert(who, r) {
|
function sponsorBlockedAlert(who, r) {
|
||||||
@@ -1088,7 +1143,9 @@ async function emailOnEvent(ev) {
|
|||||||
}
|
}
|
||||||
else if (ev.type === 'AwardPaid') {
|
else if (ev.type === 'AwardPaid') {
|
||||||
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
|
const ov = override.txInfo(ev.tx); // a level-4 override payment from the weekly payer
|
||||||
if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
const lw = !ov && launchweek.txInfo(ev.tx); // a launch week contest prize (admin-approved)
|
||||||
|
if (lw) await tell(ev.toId, 'Your launch week contest prize is paid: ' + weiToPol(ev.amountWei) + ' POL', 'You placed ' + ['1st', '2nd', '3rd', '4th', '5th'][lw.place - 1] + ' in the LinkSpin launch week contest. Your prize just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
||||||
|
else if (ov) await tell(ev.toId, 'Your Level 4 override is paid: ' + weiToPol(ev.amountWei) + ' POL', 'Your Level 4 override for the week of ' + ov.week + ' just landed in your wallet: ' + weiToPol(ev.amountWei) + ' POL. That is 3 percent of the purchases made four levels down in your line (or deeper, when the upline between was not yet qualified), paid weekly from the company wallet. You earn it while you have 5 or more qualifying buyers.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
||||||
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
else await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet');
|
||||||
}
|
}
|
||||||
else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') {
|
else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') {
|
||||||
@@ -1132,7 +1189,7 @@ async function telegramOnEvent(ev) {
|
|||||||
if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.recipientId);
|
if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.recipientId);
|
||||||
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
|
else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has <b>' + ev.newCount + '</b> qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : '');
|
||||||
else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package';
|
else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package';
|
||||||
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
|
else if (ev.type === 'AwardPaid') line = '\u{1F4B8} ' + (override.txInfo(ev.tx) ? 'Level 4 override' : launchweek.txInfo(ev.tx) ? 'Launch week contest prize' : 'Award payout') + ': <b>' + weiToPol(ev.amountWei) + ' POL</b> \u2192 ' + who(ev.toId);
|
||||||
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
|
else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts';
|
||||||
if (!line) return null;
|
if (!line) return null;
|
||||||
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
|
return line + ' \u00b7 <a href="' + tx + '">verify</a>' + (sc.telegramCtaUrl ? '\n<a href="' + sc.telegramCtaUrl + '">Join free</a>' : '');
|
||||||
@@ -1149,7 +1206,11 @@ async function tankNotifyTick() {
|
|||||||
const f = path.join(DATA_DIR, 'tank-notify.json');
|
const f = path.join(DATA_DIR, 'tank-notify.json');
|
||||||
let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {}
|
let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {}
|
||||||
const since = st.last || (Date.now() - 24 * 3600 * 1000);
|
const since = st.last || (Date.now() - 24 * 3600 * 1000);
|
||||||
const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since);
|
// sign-up grace (2026-11-07): announced when they can be adopted, 24 hours after sign-up, not when they arrive. graceFrom =
|
||||||
|
// the first run of this rule: anyone who joined before it was already announced at sign-up.
|
||||||
|
const graceFrom = st.graceFrom || (st.graceFrom = st.last || Date.now());
|
||||||
|
const fresh = [];
|
||||||
|
for (const w of tank.openedSince(await tank.waiting(), since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
||||||
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
|
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
|
||||||
if (!fresh.length) return;
|
if (!fresh.length) return;
|
||||||
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
|
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
|
||||||
@@ -1244,10 +1305,10 @@ async function tankReadyTick() {
|
|||||||
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
const clean = t => String(t || '').replace(/[<>&]/g, '');
|
||||||
const link = SITE_URL + '/tools#line';
|
const link = SITE_URL + '/tools#line';
|
||||||
if (r.fresh.length <= 3) {
|
if (r.fresh.length <= 3) {
|
||||||
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + (w.username ? '@' + clean(w.username) : 'A new member') + ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
|
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + (w.username ? '@' + clean(w.username) : 'A new member') + ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next ' + tank.leftText(w.until - Date.now()) + ': ' + link, sc.telegramEchoTopicId).catch(() => {});
|
||||||
} else { // first run after deploy (the members already linked) or a busy quarter hour: one digest, not a wall of posts
|
} else { // first run after deploy (the members already linked) or a busy quarter hour: one digest, not a wall of posts
|
||||||
const named = r.fresh.filter(w => w.username).map(w => '@' + clean(w.username));
|
const named = r.fresh.filter(w => w.username).map(w => '@' + clean(w.username));
|
||||||
await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + r.fresh.length + ' members linked a wallet and are ready to switch on payouts' + (named.length ? ': ' + named.slice(0, 12).join(', ') + (named.length > 12 ? ' and ' + (named.length - 12) + ' more' : '') : '') + '. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
|
await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + r.fresh.length + ' members linked a wallet and are ready to switch on payouts' + (named.length ? ': ' + named.slice(0, 12).join(', ') + (named.length > 12 ? ' and ' + (named.length - 12) + ' more' : '') : '') + '. Adopt them from the holding tank in the next ' + tank.leftText(Math.min(...r.fresh.map(w => w.until)) - Date.now()) + ': ' + link, sc.telegramEchoTopicId).catch(() => {});
|
||||||
}
|
}
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -1279,8 +1340,10 @@ async function telegramSendPhoto(chatId, jpeg, caption, threadId) {
|
|||||||
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
|
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] };
|
const BADGE_META = { founder: ['Founder', 'signed in before LinkSpin launched'], payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] };
|
||||||
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
|
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
|
||||||
|
// every badge a member holds: the chain milestones plus the stored Founder flag (2026-11-05)
|
||||||
|
async function badgesHeld(email) { const out = []; try { out.push(...await ads.milestonesOf(email)); } catch (e) {} try { const a = await accounts.byEmail(email); if (a && a.founder) out.push('founder'); } catch (e) {} return out; }
|
||||||
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
|
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
|
||||||
|
|
||||||
// ---- live feed (SSE) ----
|
// ---- live feed (SSE) ----
|
||||||
@@ -1360,6 +1423,8 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
|
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
|
||||||
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
||||||
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
||||||
|
// network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only)
|
||||||
|
if (req.method === 'GET' && (p === '/go/iap' || p.startsWith('/sso/') || p === '/api/sso/status') && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
||||||
|
|
||||||
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
||||||
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
|
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
|
||||||
@@ -1406,7 +1471,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
// -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin,
|
// -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin,
|
||||||
// never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging).
|
// never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging).
|
||||||
if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) {
|
if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) {
|
||||||
try { const body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); }
|
try { let body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); if (p === '/t.js') body = String(body).replace(/\/\*ls-net\*\/.*?\/\*ls-net\*\//, JSON.stringify(networkHosts())); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); }
|
||||||
}
|
}
|
||||||
if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') {
|
if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') {
|
||||||
const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' };
|
const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' };
|
||||||
@@ -1542,20 +1607,28 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit
|
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit
|
||||||
const set = [];
|
const set = [];
|
||||||
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins
|
set.push('iap.sponsor=' + tok + cookieTail); // last touch wins
|
||||||
{ const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution)
|
{ const lsid = String(u.searchParams.get('lsid') || u.searchParams.get('lsclk') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution); lsclk is what the landing tag carries from a bridge page (2026-11-07)
|
||||||
const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup
|
const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup
|
||||||
if (ang) set.push('iap.angle=' + angle + cookieTail);
|
if (ang) set.push('iap.angle=' + angle + cookieTail);
|
||||||
if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source
|
// first-touch source. A ?src= tag on the link (every mailer / traffic-source spin link carries one) is recorded with it,
|
||||||
|
// so a sign-up says "mailer.gold/mailergold" or just "mailergold" when the referrer was stripped (Marty, 2026-11-12:
|
||||||
|
// "we need the source tag so we can know where these things come from"). A tagged visit also replaces an untagged
|
||||||
|
// "direct" first touch, since the tag is the better answer.
|
||||||
|
{ const srcTag = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
|
||||||
|
const host = coach.refHost(req.headers.referer); const prev = decodeURIComponent(cookies['iap.ref'] || '');
|
||||||
|
if (!prev || (srcTag && prev === 'direct')) set.push('iap.ref=' + encodeURIComponent(srcTag ? (host && host !== 'direct' ? host + '/' : '') + srcTag : host) + cookieTail); }
|
||||||
return serveJoinPage(res, tok, ang ? angle : '', ang, set);
|
return serveJoinPage(res, tok, ang ? angle : '', ang, set);
|
||||||
}
|
}
|
||||||
// -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page
|
// -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page
|
||||||
// with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding
|
// with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding
|
||||||
// tank for adoption), the angle remembered so the welcome-back grant fires at signup, and
|
// tank for adoption), the angle remembered so the welcome-back grant fires at signup, and
|
||||||
// a forced first-touch source so link stats / admin can see the legacy arrivals.
|
// a forced first-touch source so link stats / admin can see the legacy arrivals.
|
||||||
m = /^\/from\/(faucetwave|tieroneads)$/.exec(p);
|
// /from/btc4hits (2026-11-11): the closed BTC4Hits rotator site. Its members were imported as waiting accounts, so the
|
||||||
|
// page is mostly a sign-in; angle 'b4h' is outside the fw/t1 grant rule, so no welcome-back credits are ever granted.
|
||||||
|
m = /^\/from\/(faucetwave|tieroneads|btc4hits)$/.exec(p);
|
||||||
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
|
if (m && (req.method === 'GET' || req.method === 'HEAD')) {
|
||||||
const brand = m[1];
|
const brand = m[1];
|
||||||
const key = (brand === 'faucetwave' ? 'fw' : 't1') + (String(u.searchParams.get('seg') || '').toLowerCase().startsWith('adv') ? '-adv' : '-earn');
|
const key = brand === 'btc4hits' ? 'b4h' : (brand === 'faucetwave' ? 'fw' : 't1') + (String(u.searchParams.get('seg') || '').toLowerCase().startsWith('adv') ? '-adv' : '-earn');
|
||||||
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`;
|
const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`;
|
||||||
const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page
|
const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page
|
||||||
const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail];
|
const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail];
|
||||||
@@ -1980,7 +2053,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
}
|
}
|
||||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||||
await auth.logout(req);
|
await auth.logout(req);
|
||||||
return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() });
|
return json(res, 200, { ok: true }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // signed out stays signed out: no silent network sign-in here for 12 hours
|
||||||
}
|
}
|
||||||
if (p === '/api/gas' && req.method === 'GET') {
|
if (p === '/api/gas' && req.method === 'GET') {
|
||||||
try {
|
try {
|
||||||
@@ -1997,7 +2070,9 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!s) return json(res, 200, { signedIn: false });
|
if (!s) return json(res, 200, { signedIn: false });
|
||||||
const memberId = await auth.refreshMemberId(s);
|
const memberId = await auth.refreshMemberId(s);
|
||||||
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
|
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
|
||||||
let spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
|
// Who the member sees as their sponsor (2026-11-02, Orlando saw a stranger): a member who is on the chain shows the sponsor the
|
||||||
|
// contract bound, never the referral cookie from the last link they clicked; the cookie only speaks for accounts not on chain yet.
|
||||||
|
let spdMe = await sponsorByChain(acct && acct.memberId); if (!spdMe) spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || (!(acct && Number(acct.memberId) > 0) ? parseCookies(req)['iap.sponsor'] : '')); let sponsorId = spdMe.id;
|
||||||
// holding tank (2026-10-27): the network sponsor first; nobody known = tankHold (the Switch on payouts button waits
|
// holding tank (2026-10-27): the network sponsor first; nobody known = tankHold (the Switch on payouts button waits
|
||||||
// for an adopter, 24 h at most). sponsorId keeps today's fallback so a purchase is never held.
|
// for an adopter, 24 h at most). sponsorId keeps today's fallback so a purchase is never held.
|
||||||
let tankHold = null;
|
let tankHold = null;
|
||||||
@@ -2017,6 +2092,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||||
address: s.address || (acct && acct.address) || null, memberId,
|
address: s.address || (acct && acct.address) || null, memberId,
|
||||||
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
|
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
|
||||||
|
inviteAsk: !memberId && acct ? tank.inviteAsk(acct) : null, // the Who invited you card (2026-11-07)
|
||||||
refCode: (acct && acct.code) || null, sponsorId, tankHold,
|
refCode: (acct && acct.code) || null, sponsorId, tankHold,
|
||||||
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
|
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
|
||||||
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
|
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
|
||||||
@@ -2044,7 +2120,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12)
|
let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12)
|
||||||
try {
|
try {
|
||||||
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
|
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
|
||||||
const tw = tankWaitCache.list;
|
const tw = tank.adoptableOf(tankWaitCache.list); // only people who can be adopted right now (sign-up grace, 2026-11-07)
|
||||||
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
|
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
const sc0 = siteConfig();
|
const sc0 = siteConfig();
|
||||||
@@ -2114,6 +2190,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (bc >= 5) reached.push('level3');
|
if (bc >= 5) reached.push('level3');
|
||||||
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
|
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
|
||||||
out.milestonesReached = reached;
|
out.milestonesReached = reached;
|
||||||
|
try { const fs0 = launchweek.founderState(acct || await accounts.byEmail(out.email)); out.founder = fs0.founder; out.founderPending = fs0.pending; } catch (e) {} // Founder badge: cosmetic, never in milestonesReached (no credits)
|
||||||
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
|
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
|
||||||
}
|
}
|
||||||
// who joined through this member: their invite link uses username when set,
|
// who joined through this member: their invite link uses username when set,
|
||||||
@@ -2196,6 +2273,41 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
|
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
|
||||||
return json(res, 200, await adminMember.view(a.email));
|
return json(res, 200, await adminMember.view(a.email));
|
||||||
}
|
}
|
||||||
|
// admin-made tracked links for a member (2026-11-03, Marty: a standalone copy of the games page needs LinkSpin tracking
|
||||||
|
// on every outbound link, built while he was away from his sign-in). POST { email, sourceId? | source?: { name, site },
|
||||||
|
// links: [{ name, url, label }] } -> one rotation per link on that member's account, one destination each, attached to the
|
||||||
|
// source when one is given or created. The same route serves partner placements later (one spin link per site).
|
||||||
|
if (p === '/api/admin/rotations' && req.method === 'POST') {
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const b = await readBody(req, 2e6); const a = await adminMember.resolve(String(b.email || ''));
|
||||||
|
if (!a) return json(res, 404, { error: 'No member matches that email.' });
|
||||||
|
const host = String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(h => h && !h.startsWith('www.'))[0] || SITE_HOST;
|
||||||
|
let sourceId = String(b.sourceId || '').trim();
|
||||||
|
if (!sourceId && b.source && b.source.name) { const s = await sources.create(a.email, { template: 'custom', name: String(b.source.name), site: String(b.source.site || '') }); if (s.error) return json(res, 400, { error: 'source: ' + s.error }); sourceId = s.source.id; }
|
||||||
|
const out = [];
|
||||||
|
for (const l of (Array.isArray(b.links) ? b.links : []).slice(0, 25)) {
|
||||||
|
const c = await rotator.create(a.email, { name: String(l.name || ''), fallback: String(l.url || '') }); if (c.error) { out.push({ name: l.name, error: c.error }); continue; }
|
||||||
|
// several destinations (2026-11-11, BTC4Hits rotators): l.urls = [{ url, label }] at equal weight, up to the rotator's own cap of 25
|
||||||
|
const list = Array.isArray(l.urls) && l.urls.length ? l.urls.map(x => typeof x === 'string' ? { url: x } : x) : [{ url: l.url, label: l.label }];
|
||||||
|
if (l.fallback) await rotator.update(a.email, c.rotation.id, { fallback: String(l.fallback) });
|
||||||
|
const maxDests = Math.max(25, Math.min(2000, Number(b.maxDests) || 25)); // the import may go past the member cap of 25 (BTC4Hits rotators)
|
||||||
|
let added = 0; const destErrors = []; for (const x of list) { const d = await rotator.addDest(a.email, c.rotation.id, { url: String(x.url || ''), label: String(x.label || ''), weight: 1 }, { max: maxDests, defer: true }); if (d.error) destErrors.push({ url: String(x.url || '').slice(0, 120), error: d.error }); else added++; }
|
||||||
|
await rotator.update(a.email, c.rotation.id, {}); // one save for the whole batch of destinations
|
||||||
|
if (!added) { await rotator.remove(a.email, c.rotation.id); out.push({ name: l.name, error: (destErrors[0] || {}).error || 'no destination' }); continue; }
|
||||||
|
if (sourceId) { const up = await rotator.update(a.email, c.rotation.id, { sourceId }); if (up && up.error) out.push({ name: l.name, warn: 'source not attached: ' + up.error }); }
|
||||||
|
out.push({ name: l.name, id: c.rotation.id, code: c.rotation.code, url: 'https://' + host + '/r/' + c.rotation.code, to: list[0].url, dests: added, destErrors });
|
||||||
|
}
|
||||||
|
return json(res, 200, { ok: true, email: a.email, sourceId: sourceId || null, links: out });
|
||||||
|
}
|
||||||
|
// a member's spin links + traffic sources (2026-11-11, BTC4Hits import: makes the admin route above idempotent), and removing one
|
||||||
|
if (p === '/api/admin/rotations' && (req.method === 'GET' || req.method === 'DELETE')) {
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const a = await adminMember.resolve(String(u.searchParams.get('email') || ''));
|
||||||
|
if (!a) return json(res, 404, { error: 'No member matches that email.' });
|
||||||
|
if (req.method === 'DELETE') { const r = await rotator.remove(a.email, u.searchParams.get('id')); console.log('admin removed rotation', a.email, u.searchParams.get('id')); return json(res, r.error ? 404 : 200, r); }
|
||||||
|
const host = String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(h => h && !h.startsWith('www.'))[0] || SITE_HOST;
|
||||||
|
return json(res, 200, { email: a.email, linkBase: 'https://' + host + '/r/', rotations: await rotator.list(a.email), sources: (await sources.list(a.email)).sources }, { 'Cache-Control': 'no-store' });
|
||||||
|
}
|
||||||
if (p === '/api/admin/member' && req.method === 'PATCH') {
|
if (p === '/api/admin/member' && req.method === 'PATCH') {
|
||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
@@ -2315,6 +2427,9 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
return json(res, 200, await toolkit.adminUsage());
|
return json(res, 200, await toolkit.adminUsage());
|
||||||
}
|
}
|
||||||
|
if (p === '/api/launch-week' && req.method === 'GET') { // public: launch moment + whether the contest panel is live (for /launch)
|
||||||
|
return json(res, 200, await launchweek.publicView());
|
||||||
|
}
|
||||||
if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row
|
if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row
|
||||||
const s = await auth.fromRequest(req);
|
const s = await auth.fromRequest(req);
|
||||||
const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week';
|
const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week';
|
||||||
@@ -2417,6 +2532,15 @@ const server = http.createServer(async (req, res) => {
|
|||||||
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
|
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
|
||||||
return json(res, 200, { suggest: pick });
|
return json(res, 200, { suggest: pick });
|
||||||
}
|
}
|
||||||
|
// the menu item (2026-11-11): may this member adopt, how many can be adopted right now, the at-one-time cap. Cheap: the waiting
|
||||||
|
// list is the same 60-second cache the Overview notice uses; the full list stays on /api/my/tank.
|
||||||
|
if (p === '/api/my/tank/summary' && req.method === 'GET') {
|
||||||
|
const s = await auth.fromRequest(req);
|
||||||
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
|
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
|
||||||
|
const el = await tank.eligibility(s.email);
|
||||||
|
return json(res, 200, { adopter: !!(el.ok || el.full), eligible: !!el.ok, full: !!el.full, held: el.held != null ? el.held : null, cap: tank.capOpen(), waiting: tank.adoptableOf(tankWaitCache.list).length }, { 'Cache-Control': 'no-store' });
|
||||||
|
}
|
||||||
if (p === '/api/my/tank' && req.method === 'GET') {
|
if (p === '/api/my/tank' && req.method === 'GET') {
|
||||||
const s = await auth.fromRequest(req);
|
const s = await auth.fromRequest(req);
|
||||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
@@ -2429,6 +2553,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
const key = String(u.searchParams.get('key') || '');
|
const key = String(u.searchParams.get('key') || '');
|
||||||
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
||||||
|
if (key === 'founder') return json(res, 400, { error: 'The Founder badge is not posted to Telegram.' }); // launch week: no mass badge posts (Marty 2026-11-05)
|
||||||
if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' });
|
if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' });
|
||||||
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
||||||
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
||||||
@@ -2461,7 +2586,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' });
|
||||||
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); }
|
||||||
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' });
|
||||||
if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
|
if (!(await badgesHeld(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' });
|
||||||
const a = await accounts.byEmail(s.email);
|
const a = await accounts.byEmail(s.email);
|
||||||
if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' });
|
if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' });
|
||||||
fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg);
|
fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg);
|
||||||
@@ -2480,6 +2605,19 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (r.ok) tankPickupPost(r.adopterName, r.adopteeName, false); // tell the payments topic who picked whom up (Marty, 2026-09-12)
|
if (r.ok) tankPickupPost(r.adopterName, r.adopteeName, false); // tell the payments topic who picked whom up (Marty, 2026-09-12)
|
||||||
return json(res, r.error ? 400 : 200, r);
|
return json(res, r.error ? 400 : 200, r);
|
||||||
}
|
}
|
||||||
|
// "Who invited you?" (Marty approved 2026-11-07): the signed-in member names their own sponsor. check: validate only.
|
||||||
|
if (p === '/api/my/tank/invited' && req.method === 'POST') {
|
||||||
|
const s = await auth.fromRequest(req);
|
||||||
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
|
const b = await readBody(req);
|
||||||
|
const r = await tank.nameSponsor(s.email, b.who, { check: !!b.check });
|
||||||
|
return json(res, r.error ? 400 : 200, r);
|
||||||
|
}
|
||||||
|
if (p === '/api/my/tank/invited/dismiss' && req.method === 'POST') { // "Nobody invited me": hides the card, nothing else changes
|
||||||
|
const s = await auth.fromRequest(req);
|
||||||
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
|
return json(res, 200, tank.dismissInvite(s.email));
|
||||||
|
}
|
||||||
if (p === '/api/my/tank/release' && req.method === 'POST') {
|
if (p === '/api/my/tank/release' && req.method === 'POST') {
|
||||||
const s = await auth.fromRequest(req);
|
const s = await auth.fromRequest(req);
|
||||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||||
@@ -2510,6 +2648,11 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const r = await tank.recordGift(s.email, b.email, b.tx, b.pol);
|
const r = await tank.recordGift(s.email, b.email, b.tx, b.pol);
|
||||||
return json(res, r.error ? 400 : 200, r);
|
return json(res, r.error ? 400 : 200, r);
|
||||||
}
|
}
|
||||||
|
if (p === '/api/admin/tank/grant' && req.method === 'POST') { // admin: assign N real BTC4Hits imports to an adopter on top of the cap (Marty 2026-11-11)
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const b = await readBody(req); const a = await adminMember.resolve(String(b.adopter || '')); if (!a) return json(res, 404, { error: 'No member matches that adopter.' });
|
||||||
|
tankWaitCache = null; return json(res, 200, await tank.grant(a.email, b.count));
|
||||||
|
}
|
||||||
if (p === '/api/admin/tank' && req.method === 'GET') {
|
if (p === '/api/admin/tank' && req.method === 'GET') {
|
||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
return json(res, 200, await tank.adminView());
|
return json(res, 200, await tank.adminView());
|
||||||
@@ -2621,7 +2764,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' };
|
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' };
|
||||||
if (!EXT[ct]) return json(res, 400, { error: 'Use a JPG, PNG or GIF file.' });
|
if (!EXT[ct]) return json(res, 400, { error: 'Use a JPG, PNG or GIF file.' });
|
||||||
const key = s.email + ':' + new Date().toISOString().slice(0, 10);
|
const key = s.email + ':' + new Date().toISOString().slice(0, 10);
|
||||||
if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
if (uploadCapHit(s.email, key)) return json(res, 400, { error: 'Upload limit for today reached (10 files).' });
|
||||||
let buf; try { buf = await readRaw(req, bannerspin.MAX_BYTES); } catch (e) { return json(res, 400, { error: 'That image is over 150 KB. Save it smaller (fewer colors or frames for a GIF) and try again.' }); }
|
let buf; try { buf = await readRaw(req, bannerspin.MAX_BYTES); } catch (e) { return json(res, 400, { error: 'That image is over 150 KB. Save it smaller (fewer colors or frames for a GIF) and try again.' }); }
|
||||||
const magicOk = buf.length > 16 && ((ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8'));
|
const magicOk = buf.length > 16 && ((ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8'));
|
||||||
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
|
if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' });
|
||||||
@@ -2781,7 +2924,9 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
|
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
|
||||||
// Banner Spins beside spin links (phase 3, 2026-10-20)
|
// Banner Spins beside spin links (phase 3, 2026-10-20)
|
||||||
let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); }
|
let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); }
|
||||||
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days }), { 'Cache-Control': 'no-store' });
|
// one Conversions panel (2026-11-07): site + network events and goals, each once; the tiles follow the same counts
|
||||||
|
const uni = netconv.unified(s.email, days);
|
||||||
|
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days, conversions: uni.rows, totals: Object.assign({}, spins.totals, { joins: uni.joins, wallets: uni.wallets, purchases: uni.buyers, purchaseCount: uni.purchases, goals: uni.goals }) }), { 'Cache-Control': 'no-store' });
|
||||||
}
|
}
|
||||||
// -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs).
|
// -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs).
|
||||||
if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) {
|
if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) {
|
||||||
@@ -2853,6 +2998,11 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0));
|
const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0));
|
||||||
}
|
}
|
||||||
|
if (p === '/api/hub/events' && req.method === 'POST' && hubsync.on()) { // network hub events (hubsync.js); with HUB_ENABLED off this route does not exist
|
||||||
|
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 2e6) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
|
||||||
|
const r = await hubsync.receive(req.headers, raw); return json(res, r.status, r.body);
|
||||||
|
}
|
||||||
|
if (p === '/api/admin/hubsync' && req.method === 'GET' && hubsync.on()) { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, hubsync.adminView()); }
|
||||||
// -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body),
|
// -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body),
|
||||||
// upserted into the registry; new people become shell accounts with their line, existing shells pick up a username,
|
// upserted into the registry; new people become shell accounts with their line, existing shells pick up a username,
|
||||||
// wallet or sponsor they did not have. Only the posted rows are touched.
|
// wallet or sponsor they did not have. Only the posted rows are touched.
|
||||||
@@ -2874,7 +3024,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
||||||
let a = await accounts.byEmail(e);
|
let a = await accounts.byEmail(e);
|
||||||
const created = !a;
|
const created = !a;
|
||||||
if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); }
|
if (!a) { const x = await accounts.ensure(e, '', 'carried', r.origin === 'btc4hits' ? 'btc4hits' : 'network'); if (x.created) shells++; a = await accounts.byEmail(e); } // BTC4Hits imports keep their origin (tank mail wording)
|
||||||
if (!a) continue;
|
if (!a) continue;
|
||||||
if (Object.prototype.hasOwnProperty.call(r, 'tank')) followStore.setRemote(e, r.tank); // network tank: InstantAdPay's own adoptions of them
|
if (Object.prototype.hasOwnProperty.call(r, 'tank')) followStore.setRemote(e, r.tank); // network tank: InstantAdPay's own adoptions of them
|
||||||
if (created && SF.incomingOf(r)) { const inc = SF.incomingOf(r); followStore.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'instantadpay' }); } // a new shell carries the same record (no echo)
|
if (created && SF.incomingOf(r)) { const inc = SF.incomingOf(r); followStore.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'instantadpay' }); } // a new shell carries the same record (no echo)
|
||||||
@@ -2923,9 +3073,11 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (p === '/api/partner/conv' && req.method === 'POST') {
|
if (p === '/api/partner/conv' && req.method === 'POST') {
|
||||||
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||||
const b = sg.body; const email = String(b.email || '').trim().toLowerCase();
|
const b = sg.body; const email = String(b.email || '').trim().toLowerCase();
|
||||||
|
// InstantAdPay's sign-ups, wallet links and purchases on a LinkSpin click (2026-11-07, reporting only): one answer per event
|
||||||
|
if (b.op === 'events') { const results = []; for (const ev of (Array.isArray(b.events) ? b.events.slice(0, 200) : [])) { let r = { result: 'bad' }; try { r = await netconv.record(ev); } catch (e) { console.error('netconv', e.message); return json(res, 500, { error: 'not recorded' }); } results.push({ k: String(ev && ev.k || '').slice(0, 120), result: r.result }); } return json(res, 200, { ok: true, results }); }
|
||||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' });
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' });
|
||||||
let r;
|
let r;
|
||||||
if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST });
|
if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST, network: netconv.partner(email, b.days) });
|
||||||
else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value });
|
else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value });
|
||||||
else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box)
|
else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box)
|
||||||
else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true });
|
else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true });
|
||||||
@@ -3144,8 +3296,10 @@ const server = http.createServer(async (req, res) => {
|
|||||||
memberId: m.memberId || 0,
|
memberId: m.memberId || 0,
|
||||||
sponsor: sponsorOf(m),
|
sponsor: sponsorOf(m),
|
||||||
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
|
name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member',
|
||||||
|
founder: !!m.founder, // Founder badge (cosmetic)
|
||||||
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
|
ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels
|
||||||
email: L.level === 1 ? m.email : null, // directs only
|
email: L.level === 1 ? m.email : null, // directs only
|
||||||
|
src: L.level === 1 ? (m.joinedRef || null) : null, via: L.level === 1 ? (m.joinedVia || null) : null, // where a direct came from (2026-11-13)
|
||||||
joined: m.created,
|
joined: m.created,
|
||||||
qualified: idsOf(m).some(id => qualified.has(id)),
|
qualified: idsOf(m).some(id => qualified.has(id)),
|
||||||
earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) }));
|
earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) }));
|
||||||
@@ -3172,7 +3326,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {}
|
try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {}
|
||||||
try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {}
|
try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {}
|
||||||
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
|
try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; }
|
||||||
try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; }
|
out.badges = await badgesHeld(a.email); // chain milestones + Founder
|
||||||
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
|
try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; }
|
||||||
return json(res, 200, out);
|
return json(res, 200, out);
|
||||||
}
|
}
|
||||||
@@ -3530,6 +3684,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
let socials = null; if (bought) { try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} }
|
let socials = null; if (bought) { try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} }
|
||||||
return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), bought,
|
return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), bought,
|
||||||
avatarUrl: bought ? (a.avatarUrl || null) : null, bio: bought ? (a.bio || null) : null, socials, badge,
|
avatarUrl: bought ? (a.avatarUrl || null) : null, bio: bought ? (a.bio || null) : null, socials, badge,
|
||||||
|
founder: a.founder ? { img: '/badges/badge-founder.jpg', label: 'Founder' } : null, // cosmetic Founder badge (2026-11-05)
|
||||||
joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc });
|
joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc });
|
||||||
}
|
}
|
||||||
// -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch
|
// -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch
|
||||||
@@ -3710,6 +3865,10 @@ const server = http.createServer(async (req, res) => {
|
|||||||
out.loginSlots = await ads.loginSlots(); // { max, used, queued, free, credits, days }: the Ads screen shows how many are open
|
out.loginSlots = await ads.loginSlots(); // { max, used, queued, free, credits, days }: the Ads screen shows how many are open
|
||||||
out.loginQueue = await ads.myLoginQueue(s.email); // my paid reservations: place in line + estimated start (Central)
|
out.loginQueue = await ads.myLoginQueue(s.email); // my paid reservations: place in line + estimated start (Central)
|
||||||
out.loginNext = await ads.loginNext(); // the place and estimated start a new reservation would get
|
out.loginNext = await ads.loginNext(); // the place and estimated start a new reservation would get
|
||||||
|
// a login slot is paid from ONE position (Michael Camire 2026-11-03: 1,000 credits split 618 + 382 failed with a toast he never saw):
|
||||||
|
// the screen shows each position's free purchased credits and stops the buy before it is tried
|
||||||
|
try { const pool = await ads.balances((await myMemberIds(s)).ids, s.email);
|
||||||
|
out.loginFunds = { best: (pool.best.avail || 0) + (pool.credited || 0), credited: pool.credited || 0, per: pool.per.map(x => ({ memberId: x.memberId, avail: x.avail })) }; } catch (e) { out.loginFunds = null; }
|
||||||
out.creditLog = await ads.creditLog(s.email, 20); // credit activity (login slots, reservations, refunds)
|
out.creditLog = await ads.creditLog(s.email, 20); // credit activity (login slots, reservations, refunds)
|
||||||
out.editFee = editFee(); // credits per edit after each campaign's free one (the editor says which this is)
|
out.editFee = editFee(); // credits per edit after each campaign's free one (the editor says which this is)
|
||||||
out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id));
|
out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id));
|
||||||
@@ -3742,6 +3901,8 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const fundId = pool.best.memberId || memberId;
|
const fundId = pool.best.memberId || memberId;
|
||||||
const earnedNow = String(b.type) !== 'login' ? pool.earned : 0;
|
const earnedNow = String(b.type) !== 'login' ? pool.earned : 0;
|
||||||
const budget = Math.floor(Number(b.budget) || 0);
|
const budget = Math.floor(Number(b.budget) || 0);
|
||||||
|
if (String(b.type) === 'login' && pool.per.length > 1 && budget > pool.best.avail + pool.credited && budget <= pool.total)
|
||||||
|
return json(res, 400, { error: 'Nothing was charged. A login-ad slot costs ' + budget.toLocaleString('en-US') + ' purchased credits and is paid from ONE position. Your credits are spread across ' + pool.per.length + ' positions (' + pool.per.map(x => '#' + x.memberId + ': ' + x.avail.toLocaleString('en-US')).join(', ') + ' free), so none of them holds ' + budget.toLocaleString('en-US') + ' on its own. Buy a package on one position to bring it to ' + budget.toLocaleString('en-US') + ', or let a running campaign on it finish, then try again.', loginFunds: true });
|
||||||
if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow)
|
if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow)
|
||||||
return json(res, 400, { error:'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' });
|
return json(res, 400, { error:'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' });
|
||||||
const r = await ads.createCampaign(s.email, fundId, b, ids);
|
const r = await ads.createCampaign(s.email, fundId, b, ids);
|
||||||
@@ -3962,7 +4123,8 @@ const server = http.createServer(async (req, res) => {
|
|||||||
}
|
}
|
||||||
if (p === '/api/admin/snapshot/send' && req.method === 'POST') {
|
if (p === '/api/admin/snapshot/send' && req.method === 'POST') {
|
||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r);
|
let target = ''; try { target = String(((await readBody(req)) || {}).target || '').trim(); } catch (e) {}
|
||||||
|
const r = target ? await snapshot.postTo(target) : await snapshot.post(); return json(res, r.error ? 400 : 200, r);
|
||||||
}
|
}
|
||||||
// -- level-4 override (2026-10-23): ?week=YYYY-MM-DD (any day of the week) or ?from=&to= (ms); rows=1 adds every purchase.
|
// -- level-4 override (2026-10-23): ?week=YYYY-MM-DD (any day of the week) or ?from=&to= (ms); rows=1 adds every purchase.
|
||||||
// Carries the week's payout status and the payer state; pay-now and resolve work only while the live payer is ready.
|
// Carries the week's payout status and the payer state; pay-now and resolve work only while the live payer is ready.
|
||||||
@@ -3987,6 +4149,25 @@ const server = http.createServer(async (req, res) => {
|
|||||||
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
|
const r = await override.resolve(String(b.week || ''), Number(b.memberId), String(b.action || ''), String(b.tx || ''));
|
||||||
return json(res, r && r.error ? 400 : 200, r);
|
return json(res, r && r.error ? 400 : 200, r);
|
||||||
}
|
}
|
||||||
|
// -- launch week (2026-11-05): Founder badge preview/grant + launch contest standings and the admin-approved POL payout
|
||||||
|
if (p === '/api/admin/launch-week' && req.method === 'GET') {
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
return json(res, 200, await launchweek.adminView(), { 'Cache-Control': 'no-store' });
|
||||||
|
}
|
||||||
|
if (p === '/api/admin/launch-week/founders' && req.method === 'POST') { // run the Founder grant now (refused before the launch moment)
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const r = await launchweek.grantFounders({ manual: true }); return json(res, r.error ? 400 : 200, Object.assign(r, { preview: await launchweek.founderPreview() }));
|
||||||
|
}
|
||||||
|
if (p === '/api/admin/launch-week/pay' && req.method === 'POST') { // pays the frozen places that match the list the admin confirmed; never twice
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const b = await readBody(req); if (!b || b.confirm !== true) return json(res, 400, { error: 'Send confirm: true with the places you saw.' });
|
||||||
|
const r = await launchweek.pay(b.places); return json(res, r.error ? 400 : 200, r);
|
||||||
|
}
|
||||||
|
if (p === '/api/admin/launch-week/resolve' && req.method === 'POST') {
|
||||||
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
|
const b = await readBody(req); const r = await launchweek.resolve(Number(b.place), String(b.action || ''), String(b.tx || ''));
|
||||||
|
return json(res, r.error ? 400 : 200, r);
|
||||||
|
}
|
||||||
if (p === '/api/admin/site' && req.method === 'GET') {
|
if (p === '/api/admin/site' && req.method === 'GET') {
|
||||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||||
return json(res, 200, { site: siteConfig() });
|
return json(res, 200, { site: siteConfig() });
|
||||||
@@ -4179,14 +4360,14 @@ const server = http.createServer(async (req, res) => {
|
|||||||
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
|
if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12)
|
||||||
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12)
|
if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12)
|
||||||
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
|
// -- badge share page + image: /b/<username>/<key> (OG preview = the member's composed badge) (Marty, 2026-09-13)
|
||||||
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p);
|
m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)\.jpg$/.exec(p);
|
||||||
if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg'));
|
if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg'));
|
||||||
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p);
|
m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3|founder)$/i.exec(p);
|
||||||
if (m) {
|
if (m) {
|
||||||
const un = m[1].toLowerCase(), key = m[2];
|
const un = m[1].toLowerCase(), key = m[2];
|
||||||
const a = await accounts.byUsername(un);
|
const a = await accounts.byUsername(un);
|
||||||
const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg');
|
const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg');
|
||||||
if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
if (!a || !fs.existsSync(file) || !(await badgesHeld(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
|
||||||
const [label, sub] = BADGE_META[key];
|
const [label, sub] = BADGE_META[key];
|
||||||
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg';
|
const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg';
|
||||||
@@ -4200,7 +4381,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
|
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
|
||||||
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
|
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
|
||||||
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
|
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
|
||||||
+ '<script src="/assets/common.js?v=20261101t"></script><script src="/assets/blog-page.js?v=20260912a"></script></body></html>';
|
+ '<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20260912a"></script></body></html>';
|
||||||
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
|
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
|
||||||
return res.end(html);
|
return res.end(html);
|
||||||
}
|
}
|
||||||
|
|||||||
+47
-31
@@ -1,9 +1,9 @@
|
|||||||
// Growth snapshot (Marty, 2026-09-15): once a day, a short "how the site is doing" post in the Telegram
|
// Daily snapshot (Marty, 2026-11-02): once a day, a short "how LinkSpin is doing" card in the LinkSpin Support topic
|
||||||
// payments feed (and the shared payments topic), so members watching the payout lines also see the
|
// (and any other target listed), the LinkSpin counterpart of InstantAdPay's growth snapshot. The card speaks LinkSpin:
|
||||||
// whole picture: sign-ups, purchases, POL paid out, campaigns posted, ads viewed. Every number comes
|
// spin links served, Banner Spin impressions, zone views, page views and leads, then sign-ups, purchases and POL paid.
|
||||||
// from the same tables and chain index the dashboards read. Settings: snapshotEnabled (1/0),
|
// Every number comes from the same stores the Reports screen reads. Settings: snapshotEnabled (1/0), snapshotHourUtc
|
||||||
// snapshotHourUtc (default 14 = 9 AM Central), snapshotTargets (feed,echo). State: snapshot-state.json.
|
// (default 14 = 9 AM Central), snapshotTargets (feed, support, echo). State: snapshot-state.json (lastDay), so a
|
||||||
const { SITE_URL } = require('./host');
|
// restart never double-posts.
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
@@ -15,26 +15,22 @@ function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); }
|
|||||||
function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} }
|
function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} }
|
||||||
const n = v => Number(v || 0).toLocaleString('en-US');
|
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||||
const pol = w => { try { return (Number(BigInt(w) / (10n ** 16n)) / 100).toLocaleString('en-US', { maximumFractionDigits: 0 }); } catch (e) { return '0'; } };
|
const pol = w => { try { return (Number(BigInt(w) / (10n ** 16n)) / 100).toLocaleString('en-US', { maximumFractionDigits: 0 }); } catch (e) { return '0'; } };
|
||||||
|
const safe = (fn, dflt) => { try { const v = fn(); return v == null ? dflt : v; } catch (e) { return dflt; } };
|
||||||
|
|
||||||
async function gather(now = Date.now()) {
|
async function gather(now = Date.now()) {
|
||||||
const since = now - DAY, prior = now - 2 * DAY;
|
const since = now - DAY, prior = now - 2 * DAY;
|
||||||
const s = { signups: 0, signupsPrior: 0, members: 0, wallets: 0, payoutsOn: 0, seen24h: 0,
|
const s = { signups: 0, signupsPrior: 0, members: 0, wallets: 0, payoutsOn: 0, seen24h: 0,
|
||||||
campaigns: 0, advertisers: 0, active: 0, activeAdvertisers: 0, imps: 0, viewers: 0, views: 0,
|
buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0,
|
||||||
buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0 };
|
links: null, spins: null, zones: null, pages: null };
|
||||||
if (X.db && X.db.enabled()) {
|
if (X.db && X.db.enabled()) {
|
||||||
const q = (a, b) => X.db.q(a, b || []);
|
const q = (a, b) => X.db.q(a, b || []);
|
||||||
const a = (await q('SELECT COUNT(*) total, SUM(created>=?) s24, SUM(created>=? AND created<?) sPrior, SUM(address IS NOT NULL) wallet, SUM(member_id>0) payouts, SUM(last_seen>=?) seen FROM accounts', [since, prior, since, since]))[0] || {};
|
const a = (await q('SELECT COUNT(*) total, SUM(created>=?) s24, SUM(created>=? AND created<?) sPrior, SUM(address IS NOT NULL) wallet, SUM(member_id>0) payouts, SUM(last_seen>=?) seen FROM accounts', [since, prior, since, since]))[0] || {};
|
||||||
s.members = Number(a.total || 0); s.signups = Number(a.s24 || 0); s.signupsPrior = Number(a.sPrior || 0); s.wallets = Number(a.wallet || 0); s.payoutsOn = Number(a.payouts || 0); s.seen24h = Number(a.seen || 0);
|
s.members = Number(a.total || 0); s.signups = Number(a.s24 || 0); s.signupsPrior = Number(a.sPrior || 0); s.wallets = Number(a.wallet || 0); s.payoutsOn = Number(a.payouts || 0); s.seen24h = Number(a.seen || 0);
|
||||||
const c = (await q('SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND created>=?', [since]))[0] || {};
|
} else if (X.accounts && X.accounts.listAll) {
|
||||||
s.campaigns = Number(c.n || 0); s.advertisers = Number(c.owners || 0);
|
// JSON store (production LinkSpin runs without MySQL): the same counts from the account records
|
||||||
const ac = (await q("SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND status='active'"))[0] || {};
|
const all = await X.accounts.listAll(1e6);
|
||||||
s.active = Number(ac.n || 0); s.activeAdvertisers = Number(ac.owners || 0);
|
s.members = all.length; s.signups = all.filter(a => (a.created || 0) >= since).length; s.signupsPrior = all.filter(a => (a.created || 0) >= prior && (a.created || 0) < since).length;
|
||||||
// impressions in the last 24 hours: camp_hours is keyed by UTC day + hour
|
s.wallets = all.filter(a => a.address).length; s.payoutsOn = all.filter(a => Number(a.memberId) > 0).length; s.seen24h = all.filter(a => (a.lastSeen || 0) >= since).length;
|
||||||
const d0 = new Date(since).toISOString().slice(0, 10), h0 = new Date(since).getUTCHours(), d1 = new Date(now).toISOString().slice(0, 10);
|
|
||||||
const im = (await q('SELECT SUM(n) imps FROM camp_hours WHERE (day=? AND hour>=?) OR (day>? AND day<=?)', [d0, h0, d0, d1]))[0] || {};
|
|
||||||
s.imps = Number(im.imps || 0);
|
|
||||||
const v = (await q('SELECT COUNT(*) viewers, SUM(views) views FROM daily_views WHERE day=? AND views>0', [d1]))[0] || {};
|
|
||||||
s.viewers = Number(v.viewers || 0); s.views = Number(v.views || 0);
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
for (const ev of X.chain.recentEvents(1e9)) {
|
for (const ev of X.chain.recentEvents(1e9)) {
|
||||||
@@ -42,42 +38,62 @@ async function gather(now = Date.now()) {
|
|||||||
else if (ev.type === 'MemberActivated' && ev.ts >= since) s.activations++;
|
else if (ev.type === 'MemberActivated' && ev.ts >= since) s.activations++;
|
||||||
else if (ev.type === 'TierPaid' || ev.type === 'AwardPaid') { s.lifePayouts++; s.lifePaidWei += BigInt(ev.amountWei); if (ev.ts >= since) s.paidWei += BigInt(ev.amountWei); }
|
else if (ev.type === 'TierPaid' || ev.type === 'AwardPaid') { s.lifePayouts++; s.lifePaidWei += BigInt(ev.amountWei); if (ev.ts >= since) s.paidWei += BigInt(ev.amountWei); }
|
||||||
}
|
}
|
||||||
// the index keeps a bounded event list; lifetime totals come from its running tally when present
|
|
||||||
const t = X.chain.totals ? X.chain.totals() : null;
|
const t = X.chain.totals ? X.chain.totals() : null;
|
||||||
if (t) { if (t.purchases) s.lifeBuys = Number(t.purchases); if (t.payoutWei) s.lifePaidWei = BigInt(t.payoutWei); if (t.payouts) s.lifePayouts = Number(t.payouts); }
|
if (t) { if (t.purchases) s.lifeBuys = Number(t.purchases); if (t.payoutWei) s.lifePaidWei = BigInt(t.payoutWei); if (t.payouts) s.lifePayouts = Number(t.payouts); }
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
// the LinkSpin tools, each module answers for every owner at once
|
||||||
|
s.links = safe(() => X.rotator && X.rotator.window24(since), null);
|
||||||
|
s.spins = safe(() => X.bannerspin && X.bannerspin.window24(since), null);
|
||||||
|
s.zones = safe(() => X.zones && X.zones.window24(since), null);
|
||||||
|
s.pages = safe(() => X.pages && X.pages.window24(since), null);
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
function compose(s, cta) {
|
function compose(s, cta) {
|
||||||
const trend = (cur, prev, what) => cur > prev ? ' (up from ' + n(prev) + ' ' + what + ')' : cur < prev ? ' (' + n(prev) + ' ' + what + ')' : '';
|
const trend = (cur, prev, what) => cur > prev ? ' (up from ' + n(prev) + ' ' + what + ')' : cur < prev ? ' (' + n(prev) + ' ' + what + ')' : '';
|
||||||
|
const plural = (k, one, many) => n(k) + ' ' + (k === 1 ? one : many);
|
||||||
const L = [];
|
const L = [];
|
||||||
L.push('\u{1F4C8} <b>LinkSpin</b> · 24-hour snapshot');
|
L.push('\u{1F300} <b>LinkSpin</b> · 24-hour snapshot');
|
||||||
L.push('\u{1F465} Sign-ups: <b>' + n(s.signups) + '</b>' + trend(s.signups, s.signupsPrior, 'the day before') + ' · ' + n(s.activations) + ' switched on payouts');
|
if (s.links) L.push('\u{1F517} Spin links: <b>' + n(s.links.served) + '</b> visitors sent through ' + plural(s.links.links, 'link', 'links') + ' · ' + n(s.links.unique) + ' unique · ' + n(s.links.countries) + ' countries' + (s.links.created ? ' · ' + plural(s.links.created, 'new link', 'new links') : ''));
|
||||||
|
if (s.spins) L.push('\u{1F5BC} Banner Spin: <b>' + n(s.spins.impsToday) + '</b> banner views today · ' + n(s.spins.clicks) + ' clicks · ' + n(s.spins.banners) + ' banners in ' + plural(s.spins.spins, 'spin', 'spins'));
|
||||||
|
if (s.zones) L.push('\u{1F4E1} Zones: <b>' + n(s.zones.views) + '</b> ad views on ' + plural(s.zones.zones, 'zone', 'zones') + ' · ' + n(s.zones.viewable) + ' viewable');
|
||||||
|
if (s.pages) L.push('\u{1F4C4} Pages: <b>' + n(s.pages.views) + '</b> views on ' + plural(s.pages.published, 'published page', 'published pages') + ' · ' + n(s.pages.leads) + ' leads' + (s.pages.created ? ' · ' + plural(s.pages.created, 'new page', 'new pages') : ''));
|
||||||
|
L.push('\u{1F465} Sign-ups: <b>' + n(s.signups) + '</b>' + trend(s.signups, s.signupsPrior, 'the day before') + ' · ' + n(s.activations) + ' switched on payouts · ' + n(s.seen24h) + ' signed in');
|
||||||
L.push('\u{1F9FE} Purchases: <b>' + n(s.buys) + '</b> for $' + n(Math.round(s.usd)) + trend(s.buys, s.buysPrior, 'the day before') + ' · <b>' + pol(s.paidWei) + ' POL</b> paid to members in the same transactions');
|
L.push('\u{1F9FE} Purchases: <b>' + n(s.buys) + '</b> for $' + n(Math.round(s.usd)) + trend(s.buys, s.buysPrior, 'the day before') + ' · <b>' + pol(s.paidWei) + ' POL</b> paid to members in the same transactions');
|
||||||
L.push('\u{1F4E3} Campaigns: <b>' + n(s.campaigns) + '</b> posted by ' + n(s.advertisers) + ' advertiser' + (s.advertisers === 1 ? '' : 's') + ' · ' + n(s.active) + ' running now · ' + n(s.imps) + ' ad impressions served');
|
L.push('\u{1F3C1} So far: <b>' + n(s.members) + '</b> accounts · ' + n(s.wallets) + ' wallets linked · ' + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' purchases · <b>' + pol(s.lifePaidWei) + ' POL</b> paid out in ' + n(s.lifePayouts) + ' payouts');
|
||||||
L.push('\u{1F440} Earning: <b>' + n(s.viewers) + '</b> members viewed ads today · ' + n(s.seen24h) + ' signed in');
|
if (cta) L.push('\u{1F449} ' + cta);
|
||||||
L.push('\u{1F3C1} So far: <b>' + n(s.members) + '</b> members · ' + n(s.wallets) + ' wallets linked · ' + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' purchases · <b>' + pol(s.lifePaidWei) + ' POL</b> paid out in ' + n(s.lifePayouts) + ' payouts, every one on the public ledger');
|
|
||||||
L.push('<a href="' + SITE_URL + '/ledger">Live ledger</a>' + (cta ? ' · <a href="' + cta + '">Join free</a>' : ''));
|
|
||||||
return L.join('\n');
|
return L.join('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function targetMap(sc) {
|
||||||
|
return { feed: [sc.telegramChatId, sc.telegramTopicId], support: [sc.telegramSupportChatId, sc.telegramSupportTopicId], echo: [sc.telegramEchoChatId, sc.telegramEchoTopicId] };
|
||||||
|
}
|
||||||
async function post() {
|
async function post() {
|
||||||
const sc = X.siteConfig();
|
const sc = X.siteConfig();
|
||||||
if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' };
|
if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' };
|
||||||
const s = await gather(); const text = compose(s, sc.telegramCtaUrl);
|
const s = await gather(); const text = compose(s, sc.telegramCtaUrl);
|
||||||
const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim());
|
const targets = String(sc.snapshotTargets || 'support').split(',').map(x => x.trim()).filter(Boolean);
|
||||||
let sent = 0;
|
const map = targetMap(sc); let sent = 0;
|
||||||
if (targets.includes('feed') && sc.telegramChatId) { if (await X.send(sc.telegramChatId, text, sc.telegramTopicId)) sent++; }
|
for (const name of targets) {
|
||||||
if (targets.includes('echo') && sc.telegramEchoChatId) { if (await X.send(sc.telegramEchoChatId, text, sc.telegramEchoTopicId)) sent++; }
|
const t = map[name]; if (!t) continue;
|
||||||
|
if (!t[0]) { console.warn('snapshot: target "' + name + '" is listed but has no chat id, nothing sent'); continue; }
|
||||||
|
if (await X.send(t[0], text, t[1])) sent++;
|
||||||
|
}
|
||||||
const st = state(); st.lastPost = Date.now(); st.lastDay = new Date().toISOString().slice(0, 10); setState(st);
|
const st = state(); st.lastPost = Date.now(); st.lastDay = new Date().toISOString().slice(0, 10); setState(st);
|
||||||
return { ok: true, sent, text };
|
return { ok: true, sent, text };
|
||||||
}
|
}
|
||||||
|
// one destination by name, for a one-off post (admin: POST /api/admin/snapshot/send with {target})
|
||||||
|
async function postTo(name) {
|
||||||
|
const sc = X.siteConfig(); if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' };
|
||||||
|
const t = targetMap(sc)[name]; if (!t || !t[0]) return { error: 'No chat id for target ' + name + '.' };
|
||||||
|
const text = compose(await gather(), sc.telegramCtaUrl);
|
||||||
|
const ok = await X.send(t[0], text, t[1]); return { ok: !!ok, sent: ok ? 1 : 0, target: name, text };
|
||||||
|
}
|
||||||
|
|
||||||
// every 10 minutes: post once a day at or after snapshotHourUtc (a restart never double-posts)
|
// every 10 minutes: post once a day at or after snapshotHourUtc (a restart never double-posts)
|
||||||
async function tick() {
|
async function tick() {
|
||||||
const sc = X.siteConfig();
|
const sc = X.siteConfig();
|
||||||
if (String(sc.snapshotEnabled || '1') !== '1' || !sc.telegramBotToken) return;
|
if (String(sc.snapshotEnabled || '0') !== '1' || !sc.telegramBotToken) return;
|
||||||
const hour = Number(sc.snapshotHourUtc == null || sc.snapshotHourUtc === '' ? 14 : sc.snapshotHourUtc);
|
const hour = Number(sc.snapshotHourUtc == null || sc.snapshotHourUtc === '' ? 14 : sc.snapshotHourUtc);
|
||||||
const now = new Date(); const day = now.toISOString().slice(0, 10);
|
const now = new Date(); const day = now.toISOString().slice(0, 10);
|
||||||
if (now.getUTCHours() < hour) return;
|
if (now.getUTCHours() < hour) return;
|
||||||
@@ -87,4 +103,4 @@ async function tick() {
|
|||||||
|
|
||||||
async function preview() { const sc = X.siteConfig(); return compose(await gather(), sc.telegramCtaUrl); }
|
async function preview() { const sc = X.siteConfig(); return compose(await gather(), sc.telegramCtaUrl); }
|
||||||
|
|
||||||
module.exports = { init, gather, compose, post, tick, preview };
|
module.exports = { init, gather, compose, post, postTo, tick, preview };
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
|
||||||
const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin'];
|
const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin', 'invited']; // invited = the member named who invited them (tank.js nameSponsor, 2026-11-07)
|
||||||
const WINDOW_MS = 15 * 60 * 1000;
|
const WINDOW_MS = 15 * 60 * 1000;
|
||||||
const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 }
|
const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 }
|
||||||
const n = v => String(v == null ? '' : v).trim().toLowerCase();
|
const n = v => String(v == null ? '' : v).trim().toLowerCase();
|
||||||
|
|||||||
@@ -12,16 +12,25 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const db = require('./db');
|
const db = require('./db');
|
||||||
|
|
||||||
const CAP_OPEN = 2; // open adoptions per adopter
|
// How many people an adopter may hold from the tank AT ONE TIME (Marty 2026-11-11, for the ~1,200 BTC4Hits imports, 6 then 10 the same day; was 2 open
|
||||||
|
// adoptions): open adoptions whose person has not switched payouts on yet (no member id). Activating frees the slot at once; the
|
||||||
|
// 7-day window closes the rest as before. Site setting tankAdoptCap, default 10.
|
||||||
|
const CAP_DEFAULT = 10; let capFn = () => CAP_DEFAULT;
|
||||||
|
const capOpen = () => { const n = Math.round(Number(capFn())); return n >= 1 && n <= 50 ? n : CAP_DEFAULT; };
|
||||||
|
async function holding(open) { const out = []; for (const ad of open || []) { const a = await accounts.byEmail(ad.adoptee); if (!(a && Number(a.memberId) > 0)) out.push(ad); } return out; }
|
||||||
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
||||||
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
|
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
|
||||||
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
|
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
|
||||||
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
|
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
|
||||||
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js)
|
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js), and a record of a
|
||||||
const NOT_COUNTED = ['released', 'conflict'];
|
// member naming who invited them (nobody adopted them; nameSponsor below)
|
||||||
|
const NOT_COUNTED = ['released', 'conflict', 'invited'];
|
||||||
const MIN_OWN_BUY_CENTS = 2500; // adopter must have bought a qualifying ($25+) package themselves
|
const MIN_OWN_BUY_CENTS = 2500; // adopter must have bought a qualifying ($25+) package themselves
|
||||||
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
|
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
|
||||||
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
||||||
|
const GRACE_MS = 24 * 3600 * 1000; // nobody adopts a new sign-up by hand for this long after `created`, so they can say who invited them (Marty 2026-11-07)
|
||||||
|
const BRAND = 'LinkSpin';
|
||||||
|
const LINE_URL = () => siteUrl + '/tools#line';
|
||||||
|
|
||||||
let DATA_DIR = '.', accounts, chain, messages, mailer, siteUrl = SITE_URL;
|
let DATA_DIR = '.', accounts, chain, messages, mailer, siteUrl = SITE_URL;
|
||||||
|
|
||||||
@@ -49,10 +58,10 @@ const D = {
|
|||||||
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
||||||
return rows.map(rowA);
|
return rows.map(rowA);
|
||||||
},
|
},
|
||||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n); },
|
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n); },
|
||||||
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
|
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
|
||||||
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
|
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
|
||||||
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n) > 0; },
|
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n) > 0; },
|
||||||
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
|
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
|
||||||
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
|
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
|
||||||
async setMark(lead, f) {
|
async setMark(lead, f) {
|
||||||
@@ -63,7 +72,7 @@ const D = {
|
|||||||
const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null });
|
const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null });
|
||||||
const impl = () => db.enabled() ? D : J;
|
const impl = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load();
|
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; if (opts.capOpen) capFn = opts.capOpen; J.load();
|
||||||
hooks = opts.hooks || {}; RS.st = null; RS.load(); }
|
hooks = opts.hooks || {}; RS.st = null; RS.load(); }
|
||||||
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to InstantAdPay
|
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to InstantAdPay
|
||||||
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
|
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
|
||||||
@@ -80,12 +89,13 @@ const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or
|
|||||||
|
|
||||||
// waiting list: newest sign-in first so a live one is easy to spot
|
// waiting list: newest sign-in first so a live one is easy to spot
|
||||||
async function waiting() {
|
async function waiting() {
|
||||||
const all = await accounts.listAll(2000);
|
const all = await accounts.listAll(1e6); // was 2000: newest-first, so once the site passed 2000 accounts (BTC4Hits import 2026-11-11) older tank members fell off the list
|
||||||
return all.filter(a => inTank(a) && !remoteOpen(a.email)).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: !!a.address,
|
return all.filter(a => inTank(a) && !remoteOpen(a.email)).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: !!a.address,
|
||||||
// wallet linked = ready to switch on payouts, the plain activation held for an adopter (24-hour clock, autoAssign after that)
|
// wallet linked = ready to switch on payouts, the plain activation held for an adopter (24-hour clock, autoAssign after that)
|
||||||
|
opensAt: inGrace(a) ? graceEnd(a) : 0, // new sign-up: nobody can adopt them by hand before this (0 = open now)
|
||||||
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
|
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
|
||||||
// ready members first (least time left first), then newest sign-in
|
// open before the sign-up grace ones, ready members first (least time left first), then newest sign-in
|
||||||
.sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || (a.ready && b.ready ? a.readyAt - b.readyAt : 0) || (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
.sort((a, b) => (a.opensAt ? 1 : 0) - (b.opensAt ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || (a.ready && b.ready ? a.readyAt - b.readyAt : 0) || (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
||||||
}
|
}
|
||||||
|
|
||||||
// has this member bought a $25 or larger package themselves? (the qualifying-for-yourself buy)
|
// has this member bought a $25 or larger package themselves? (the qualifying-for-yourself buy)
|
||||||
@@ -94,13 +104,13 @@ function hasOwnBuy(memberId) {
|
|||||||
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && ev.buyerId === memberId && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS) return true;
|
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && ev.buyerId === memberId && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS) return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
async function eligibility(email) {
|
async function eligibility(email, opts) {
|
||||||
const a = await accounts.byEmail(email);
|
const a = await accounts.byEmail(email);
|
||||||
if (!a) return { ok: false, reason: 'Sign in first.' };
|
if (!a) return { ok: false, reason: 'Sign in first.' };
|
||||||
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $25 package to adopt from the tank.' };
|
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $25 package to adopt from the tank.' };
|
||||||
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $25 or larger package first. Adopting is for members who have made that move themselves.' };
|
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $25 or larger package first. Adopting is for members who have made that move themselves.' };
|
||||||
const open = await impl().open(a.email);
|
const open = await impl().open(a.email); const held = await holding(open); const cap = capOpen();
|
||||||
if (open.length >= CAP_OPEN) return { ok: false, reason: 'You have ' + CAP_OPEN + ' open adoptions. Help one of them link a wallet or buy, and a slot frees up.', full: true };
|
if (held.length >= cap && !(opts && opts.skipCap)) return { ok: false, reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold. A slot opens when one of them switches on payouts, or when their 7-day window ends.', full: true, cap, held: held.length };
|
||||||
return { ok: true, account: a, open };
|
return { ok: true, account: a, open };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,13 +122,13 @@ async function view(email) {
|
|||||||
const a = await accounts.byEmail(ad.adoptee);
|
const a = await accounts.byEmail(ad.adoptee);
|
||||||
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
|
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
|
||||||
}
|
}
|
||||||
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, waiting: await waiting(), mine };
|
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, graceHours: GRACE_MS / 3600000, waiting: await waiting(), mine };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function adopt(adopterEmail, who, note, opts) {
|
async function adopt(adopterEmail, who, note, opts) {
|
||||||
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
||||||
const e = String(adopterEmail || '').toLowerCase();
|
const e = String(adopterEmail || '').toLowerCase();
|
||||||
const el = await eligibility(e);
|
const el = await eligibility(e, { skipCap: !!(opts && opts.skipCap) }); // skipCap: an admin grant on top of the cap (Marty 2026-11-11)
|
||||||
if (!el.ok) return { error: el.reason };
|
if (!el.ok) return { error: el.reason };
|
||||||
const me = el.account;
|
const me = el.account;
|
||||||
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
|
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
|
||||||
@@ -126,13 +136,17 @@ async function adopt(adopterEmail, who, note, opts) {
|
|||||||
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
||||||
if (!target) return { error: 'That member is no longer in the tank.' };
|
if (!target) return { error: 'That member is no longer in the tank.' };
|
||||||
if (target.email === e) return { error: 'That is you.' };
|
if (target.email === e) return { error: 'That is you.' };
|
||||||
|
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
|
||||||
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
|
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
|
||||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
||||||
const token = me.username || me.code || String(me.memberId);
|
const token = me.username || me.code || String(me.memberId);
|
||||||
const r = await setSponsor(target.email, token, 'adopt');
|
const r = await setSponsor(target.email, token, 'adopt');
|
||||||
if (r.error) return r;
|
if (r.error) return r;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined LinkSpin without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
const tgt0 = await accounts.byEmail(target.email); const b4h = !!(tgt0 && (tgt0.joinedRef === 'btc4hits' || tgt0.joinedVia === 'btc4hits')); // a BTC4Hits import (2026-11-11): they never joined LinkSpin themselves
|
||||||
|
const text = String(note || '').trim().slice(0, 600) || (b4h
|
||||||
|
? 'Hi, I am ' + nameOf(me) + '. Your BTC4Hits account moved to LinkSpin without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.'
|
||||||
|
: 'Hi, I am ' + nameOf(me) + '. You joined LinkSpin without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
||||||
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = clock(); rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
|
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = clock(); rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
|
||||||
// wallet already linked: the engine switches their payouts on under the adopter right away (Marty approved 2026-10-27)
|
// wallet already linked: the engine switches their payouts on under the adopter right away (Marty approved 2026-10-27)
|
||||||
@@ -147,7 +161,9 @@ async function adopt(adopterEmail, who, note, opts) {
|
|||||||
if (mailer && mailer.hasKey()) {
|
if (mailer && mailer.hasKey()) {
|
||||||
try {
|
try {
|
||||||
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on LinkSpin',
|
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on LinkSpin',
|
||||||
'You joined LinkSpin without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + payLine + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nLinkSpin');
|
b4h
|
||||||
|
? 'BTC4Hits has moved to LinkSpin, and your BTC4Hits account came with you. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + payLine + '\n\nSign in with the email you used on BTC4Hits (we send you a code, no password) and reply in your member area: ' + siteUrl + '/from/btc4hits\n\nLinkSpin'
|
||||||
|
: 'You joined LinkSpin without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + payLine + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nLinkSpin');
|
||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
if (auto) {
|
if (auto) {
|
||||||
try {
|
try {
|
||||||
@@ -475,10 +491,10 @@ async function autoAssignRun() {
|
|||||||
let done = null;
|
let done = null;
|
||||||
for (const c of pool) {
|
for (const c of pool) {
|
||||||
if (c.a.email === e) continue;
|
if (c.a.email === e) continue;
|
||||||
if ((await impl().open(c.a.email)).length >= CAP_OPEN) continue;
|
if ((await holding(await impl().open(c.a.email))).length >= capOpen()) continue;
|
||||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
|
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
|
||||||
if (await inDownlineOf(e, c.a)) continue;
|
if (await inDownlineOf(e, c.a)) continue;
|
||||||
const msg = 'Hi, I am ' + nameOf(c.a) + '. You joined LinkSpin without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
|
const msg = 'Hi, I am ' + nameOf(c.a) + '. ' + ((a.joinedVia === 'btc4hits' || a.joinedRef === 'btc4hits') ? 'Your BTC4Hits account moved to LinkSpin' : 'You joined LinkSpin') + ' without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
|
||||||
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
|
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
|
||||||
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
|
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
|
||||||
}
|
}
|
||||||
@@ -492,7 +508,7 @@ async function autoAssignRun() {
|
|||||||
out.held++;
|
out.held++;
|
||||||
if (!rec.noAdopterAlerted) {
|
if (!rec.noAdopterAlerted) {
|
||||||
rec.noAdopterAlerted = clock(); RS.save();
|
rec.noAdopterAlerted = clock(); RS.save();
|
||||||
if (hooks.adminAlert && await claimOnce('tankalert:' + e + ':' + rec.readyAt)) { try { await hooks.adminAlert('LinkSpin holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $25+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not on a no-payout chain). Their payouts stay switched off (a purchase still goes ahead), never under the company. Adopt them from More > My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
if (hooks.adminAlert && await claimOnce('tankalert:' + e + ':' + rec.readyAt)) { try { await hooks.adminAlert('LinkSpin holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $25+ package, fewer than ' + capOpen() + ' tank members held, signed in within 7 days, not on a no-payout chain). Their payouts stay switched off (a purchase still goes ahead), never under the company. Adopt them from More > My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -510,9 +526,11 @@ async function readyTick() {
|
|||||||
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
||||||
if (remoteOpen(a.email)) continue;
|
if (remoteOpen(a.email)) continue;
|
||||||
const rec = markReady(a);
|
const rec = markReady(a);
|
||||||
if (rec && !rec.notified) {
|
// Sign-up grace (2026-11-07): no "adopt them" post for someone who cannot be adopted yet; announced when the grace ends,
|
||||||
|
// and not at all when the safety net takes them in this same tick (nothing left for anyone to do)
|
||||||
|
if (rec && !rec.notified && !inGrace(a)) {
|
||||||
rec.notified = clock();
|
rec.notified = clock();
|
||||||
const iap = hooks.iapOwns ? await Promise.resolve(hooks.iapOwns(a.email)).catch(() => false) : false;
|
const iap = clock() < rec.readyAt + READY_MS - TICK_MS ? (hooks.iapOwns ? await Promise.resolve(hooks.iapOwns(a.email)).catch(() => false) : false) : true;
|
||||||
if (!iap && await claimOnce('tankready:' + a.email + ':' + rec.readyAt)) fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS });
|
if (!iap && await claimOnce('tankready:' + a.email + ':' + rec.readyAt)) fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -567,11 +585,103 @@ async function liftPendingRun() {
|
|||||||
}
|
}
|
||||||
function alignedRecent(n) { return RS.load().aligned.slice(-(n || 50)).reverse(); }
|
function alignedRecent(n) { return RS.load().aligned.slice(-(n || 50)).reverse(); }
|
||||||
|
|
||||||
|
// ── sign-up grace + "Who invited you?" (Marty approved 2026-11-07: "24-hour grace plus the prompt") ──
|
||||||
|
// Nov 2: @santoridaviss signed up with no referral at 10:35 PM, was adoptable at 2:24 AM and adopted at 3:36 AM, before he
|
||||||
|
// could say who invited him. So:
|
||||||
|
// GRACE: for 24 hours from the account's `created`, nobody can adopt the person BY HAND. They stay on the waiting list with
|
||||||
|
// opensAt set (the card shows "Opens in ...", no Adopt button). The dates are each site's own account dates. Only sign-up
|
||||||
|
// counts: someone back in the tank later (released, rescued, window ended) is past it.
|
||||||
|
// The safety net does not wait for the grace (opts.auto skips it): Marty's rule is a wallet-linked member is held for no
|
||||||
|
// longer than 24 hours, so autoAssign keeps its clock from the wallet link. Wallet linked in the first 15 minutes: the
|
||||||
|
// rotation can fire up to 15 minutes before the grace ends, and hand adoption never opens for them. Wallet linked in the
|
||||||
|
// first hour: hand adoption opens at 24 hours and the rotation takes them about an hour after that.
|
||||||
|
// Notices: readyTick announces a ready member only once they can be adopted, and only when time is left (adoptableOf and
|
||||||
|
// openedSince keep the Overview note, the arrivals post and the weekly email to people who are open too).
|
||||||
|
// PROMPT: a tank member can name who invited them. nameSponsor() goes through setSponsor like adopt(), so it follows to the
|
||||||
|
// other site and clears the hold the same way, but it is the member's own choice: only ever for the signed-in member,
|
||||||
|
// never an open adoption (no 7-day window, no fall-back, no count toward the two), recorded as status 'invited'.
|
||||||
|
function graceEnd(a) { if (a && a.joinedRef === 'btc4hits') return 0; /* BTC4Hits imports (2026-11-11) never signed up here, so there is no inviter to wait for: adoptable at once (Marty: adopters on standby) */ return (Number(a && a.created) || 0) + GRACE_MS; }
|
||||||
|
function inGrace(a) { return graceEnd(a) > clock(); }
|
||||||
|
function leftText(ms) { const m = Math.max(1, Math.ceil(Number(ms) / 60000) || 1); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; }
|
||||||
|
const adoptableOf = list => (list || []).filter(w => !(w.opensAt > clock()));
|
||||||
|
async function adoptable() { return adoptableOf(await waiting()); }
|
||||||
|
// people whose grace ended after `since` (the arrivals post: announced when they can be adopted, not when they sign up)
|
||||||
|
function openedSince(list, since) { const now = clock(); return (list || []).filter(w => { const t = (Number(w.joined) || 0) + GRACE_MS; return t > since && t <= now; }); }
|
||||||
|
// what the dashboard needs: null = no card. dismissed = they tapped "Nobody invited me" (a small link brings the card back).
|
||||||
|
function inviteAsk(a) {
|
||||||
|
if (!a || !inTank(a) || remoteOpen(a.email)) return null;
|
||||||
|
return { dismissed: !!(RS.load().noInvite || {})[String(a.email || '').toLowerCase()] };
|
||||||
|
}
|
||||||
|
function dismissInvite(email) { const st = RS.load(); st.noInvite = st.noInvite || {}; st.noInvite[String(email || '').toLowerCase()] = clock(); RS.save(); return { ok: true }; }
|
||||||
|
// someone in the named person's line (them first) already has a contract position? Otherwise the member would be walked up to
|
||||||
|
// the company at their first activation, the one thing the tank exists to stop
|
||||||
|
async function firstOnContract(sp) {
|
||||||
|
let cur = sp; const seen = new Set();
|
||||||
|
for (let i = 0; cur && i < 60; i++) { if (Number(cur.memberId) > 0) return cur; if (seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// opts.check: every refusal, nothing written (the card asks "is this them?" before the real call)
|
||||||
|
async function nameSponsor(email, who, opts) {
|
||||||
|
const e = String(email || '').toLowerCase(); const check = !!(opts && opts.check);
|
||||||
|
const LOCKED = 'Your payouts are already on, so your sponsor is locked on the contract.';
|
||||||
|
let a = await accounts.byEmail(e);
|
||||||
|
if (!a) return { error: 'Sign in first.' };
|
||||||
|
if (Number(a.memberId) > 0) return { error: LOCKED };
|
||||||
|
if (a.sponsorRef) return { error: 'You already have a sponsor.' };
|
||||||
|
if (a.address) { // wallet on the contract already, member number not saved yet
|
||||||
|
if (hooks.bound) { const id = await Promise.resolve(hooks.bound(a)).catch(() => -1); if (id < 0) return { error: 'Could not check the contract just now. Try again in a minute.' }; if (id > 0) return { error: LOCKED }; }
|
||||||
|
else if (hooks.activated && await Promise.resolve(hooks.activated(a)).catch(() => false)) return { error: LOCKED };
|
||||||
|
}
|
||||||
|
if (remoteOpen(e)) return { error: 'You were just picked up on ' + OTHER + ', so you already have a sponsor.' };
|
||||||
|
const al = await alignToNetwork(a).catch(() => null); // one identity: the sponsor the network already knows comes first
|
||||||
|
if (al) return { error: 'You already have a sponsor on the network: ' + al.toName + '.', aligned: true };
|
||||||
|
const key = String(who || '').trim().toLowerCase().replace(/^@+/, '');
|
||||||
|
if (!key) return { error: 'Type the username of the person who invited you.' };
|
||||||
|
const sp = /^[a-z0-9_]{3,20}$/.test(key) ? await accounts.byUsername(key) : null;
|
||||||
|
if (!sp || (accounts.isUnclaimedShell && accounts.isUnclaimedShell(sp))) return { error: 'No member here has the username ' + key + '. Check the spelling with the person who invited you.' };
|
||||||
|
if (String(sp.email).toLowerCase() === e) return { error: 'That is you. Type the username of the person who invited you.' };
|
||||||
|
const bar = hooks.excluded || hooks.isSuspended;
|
||||||
|
if (bar && bar(sp.email)) return { error: nameOf(sp) + ' cannot take new members right now.' };
|
||||||
|
if (await inDownlineOf(e, sp)) return { error: nameOf(sp) + ' is in your own line, so they cannot be your sponsor.' };
|
||||||
|
const payee = await firstOnContract(sp);
|
||||||
|
if (!payee) return { error: nameOf(sp) + ' has not switched on payouts yet, and nobody above them has either, so you cannot go under them yet. Ask them to switch on payouts, then come back here.' };
|
||||||
|
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { error: nameOf(sp) + ' cannot take new members right now.' };
|
||||||
|
if (check) return { ok: true, check: true, name: nameOf(sp) };
|
||||||
|
a = await accounts.byEmail(e);
|
||||||
|
if (!a || !inTank(a)) return { error: 'You already have a sponsor.' };
|
||||||
|
const token = sp.username || sp.code || String(sp.memberId);
|
||||||
|
const r = await setSponsor(e, token, 'invited', 'named by the member on the Who invited you card');
|
||||||
|
if (r && r.error) return r;
|
||||||
|
const now = clock();
|
||||||
|
const ad = await impl().add({ adoptee: e, adopter: String(sp.email).toLowerCase(), ts: now, expires: now, status: 'invited', note: 'named by the member on the Who invited you card' });
|
||||||
|
{ const rr = RS.load().ready[e]; if (rr && !rr.done) { rr.done = now; rr.namedSponsor = sp.email; RS.save(); } } // the hold lifts: their sponsor resolves now
|
||||||
|
const name = nameOf(a);
|
||||||
|
{ const tg = await accounts.byEmail(e); if (tg && tg.address && !(Number(tg.memberId) > 0) && hooks.lifted) { markLift(e); liftRun(e).catch(err => console.error('tank lift', err.message)); } } // wallet already linked: the engine switches payouts on under them, same as an adoption
|
||||||
|
const subject = 'You have a new referral on ' + BRAND;
|
||||||
|
const text = name + ' joined ' + BRAND + ' without a sponsor link and told us you invited them, so they are on your team from today. Say hello and help them with their first steps: ' + LINE_URL();
|
||||||
|
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, subject, text + '\n\n' + BRAND); } catch (err) {} }
|
||||||
|
if (hooks.notify) { try { await hooks.notify(sp.email, subject, text); } catch (err) {} }
|
||||||
|
return { ok: true, name: nameOf(sp), sponsorEmail: sp.email, member: name };
|
||||||
|
}
|
||||||
|
|
||||||
async function adminView() {
|
async function adminView() {
|
||||||
const recent = await impl().recent(200);
|
const recent = await impl().recent(200);
|
||||||
const names = {};
|
const names = {};
|
||||||
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
|
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
|
||||||
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30) };
|
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30) };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, view, adopt, holdFor, gate, markReady, readyRec, readyTick, autoAssign, alignToNetwork, alignedRecent, setClock, eligibility, inTank, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
// admin grant (Marty 2026-11-11): the adopters who picked up the Yandex batch from the BTC4Hits import keep those, and get the same number of
|
||||||
|
// real imports assigned on top of the cap. Picks BTC4Hits imports from the waiting list, skipping the bot patterns (yandex, dotted gmail).
|
||||||
|
const JUNK = e => /@yandex\./i.test(e) || (/@gmail\.com$/i.test(e) && (e.split('@')[0].match(/\./g) || []).length >= 3);
|
||||||
|
async function grant(adopterEmail, count) {
|
||||||
|
const out = []; let left = Math.max(0, Math.min(20, Number(count) || 0));
|
||||||
|
for (const w of await waiting()) {
|
||||||
|
if (!left) break; if (JUNK(w.email)) continue;
|
||||||
|
const a = await accounts.byEmail(w.email); if (!a || !(a.joinedRef === 'btc4hits' || a.joinedVia === 'btc4hits')) continue;
|
||||||
|
const r = await adopt(adopterEmail, w.email, '', { auto: true, skipCap: true, recordNote: 'Admin grant (BTC4Hits import)' });
|
||||||
|
out.push({ adoptee: mask(w.email), ok: !r.error, error: r.error || undefined }); if (!r.error) left--;
|
||||||
|
}
|
||||||
|
return { adopter: adopterEmail, assigned: out.filter(x => x.ok).length, tried: out };
|
||||||
|
}
|
||||||
|
module.exports = { grant, init, view, adopt, holdFor, gate, markReady, readyRec, readyTick, autoAssign, alignToNetwork, alignedRecent, setClock, eligibility, inTank, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||||
|
|||||||
+1
-1
@@ -54,7 +54,7 @@ function compose({ subject, intro, noteIds, closing }, acct) {
|
|||||||
|
|
||||||
let running = null;
|
let running = null;
|
||||||
async function send(input, opts) {
|
async function send(input, opts) {
|
||||||
const noteIds = (input.noteIds || []).map(String); if (!noteIds.length) return { error: 'Pick at least one release note.' };
|
const noteIds = (input.noteIds || []).map(String); if (!noteIds.length && !String(input.intro || '').trim()) return { error: 'Write an intro or pick at least one release note.' }; // campaign emails are intro-only (LinkSpin launch, 2026-11-05)
|
||||||
if (!R.mailer.hasKey()) return { error: 'The mailer is not configured on this server.' };
|
if (!R.mailer.hasKey()) return { error: 'The mailer is not configured on this server.' };
|
||||||
if (opts && opts.test) {
|
if (opts && opts.test) {
|
||||||
const to = R.adminEmail; if (!to) return { error: 'No admin email configured.' };
|
const to = R.adminEmail; if (!to) return { error: 'No admin email configured.' };
|
||||||
|
|||||||
@@ -139,6 +139,11 @@ function adminAll() {
|
|||||||
return { id: z.id, name: z.name, site: z.site, size: z.size, tier: tierOf(z), active: !!z.active, paused: !!z.adminPaused, note: z.adminNote || '', owner: z.owner, created: z.created,
|
return { id: z.id, name: z.name, site: z.site, size: z.size, tier: tierOf(z), active: !!z.active, paused: !!z.adminPaused, note: z.adminNote || '', owner: z.owner, created: z.created,
|
||||||
views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(seen / imps.length * 100) : null, clicks30: imps.filter(i => i.k).length, offsite30: imps.filter(i => i.off).length, credits: z.credits || 0, status: st.state, statusLabel: st.label, lastSeen: last[z.id] || 0 }; });
|
views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(seen / imps.length * 100) : null, clicks30: imps.filter(i => i.k).length, offsite30: imps.filter(i => i.off).length, credits: z.credits || 0, status: st.state, statusLabel: st.label, lastSeen: last[z.id] || 0 }; });
|
||||||
}
|
}
|
||||||
|
// site-wide figures for the daily snapshot: real impressions inside the `since` window and new zones
|
||||||
|
function window24(since) {
|
||||||
|
const imps = J.db.imps.filter(i => i.ts >= since && !i.bot);
|
||||||
|
return { zones: J.db.zones.length, created: J.db.zones.filter(z => (z.created || 0) >= since).length, views: imps.length, viewable: imps.filter(i => i.ok).length };
|
||||||
|
}
|
||||||
function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; }
|
function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; }
|
||||||
// -- publisher program totals (Reports screen + the public strip): the last N days, Central days, per day and per zone.
|
// -- publisher program totals (Reports screen + the public strip): the last N days, Central days, per day and per zone.
|
||||||
// "live" = switched on, not admin-paused, and seen by a real visitor inside the window. Credits are read from the pay log
|
// "live" = switched on, not admin-paused, and seen by a real visitor inside the window. Credits are read from the pay log
|
||||||
@@ -164,4 +169,4 @@ function publisherPublic() {
|
|||||||
rates: { viewsPerCredit: s.viewsPerCredit, nasViewsPerCredit: s.nasViewsPerCredit, nasViewsPerCreditVerified: s.nasViewsPerCreditVerified, capPerVisitorDay: s.capPerVisitorDay }, warmup: WARMUP, holdRatio: HOLD_RATIO, updated: Date.now() };
|
rates: { viewsPerCredit: s.viewsPerCredit, nasViewsPerCredit: s.nasViewsPerCredit, nasViewsPerCreditVerified: s.nasViewsPerCreditVerified, capPerVisitorDay: s.capPerVisitorDay }, warmup: WARMUP, holdRatio: HOLD_RATIO, updated: Date.now() };
|
||||||
pubCache = { ts: Date.now(), data }; return data;
|
pubCache = { ts: Date.now(), data }; return data;
|
||||||
}
|
}
|
||||||
module.exports = { init, SIZES, NAS_SIZES, TIERS, WARMUP, HOLD_RATIO, settings, tierOf, rateFor, nasFrame, list, create, update, tag, serve, seen, click, totals, publisherTotals, publisherPublic, adminList, adminSet, adminAll };
|
module.exports = { init, SIZES, NAS_SIZES, TIERS, WARMUP, HOLD_RATIO, settings, tierOf, rateFor, nasFrame, list, create, update, tag, serve, seen, click, totals, window24, publisherTotals, publisherPublic, adminList, adminSet, adminAll };
|
||||||
|
|||||||
Reference in New Issue
Block a user