Compare commits
33 Commits
86007f0784
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0785d4b41a | |||
| 35aa2f6514 | |||
| 255e399272 | |||
| 994a2054d8 | |||
| bca3666ee2 | |||
| a6c36aeca1 | |||
| 61c0ccc48a | |||
| 2217fd2c80 | |||
| 7edc1a25b0 | |||
| 4d22ae72c8 | |||
| e62545994f | |||
| b5df8a2820 | |||
| bd5ed4e370 | |||
| ae39e05fc5 | |||
| 5613d10224 | |||
| e0ece93e9d | |||
| 03d87fbb79 | |||
| 77e18fd230 | |||
| 6c5851b4d5 | |||
| 1db7699e25 | |||
| aa7595a9cd | |||
| 2ede19a13d | |||
| daf24a8f81 | |||
| 1b0e324176 | |||
| b2669cfed7 | |||
| 73bee6c826 | |||
| 60dc4d537d | |||
| fbf7d87030 | |||
| f4789156b8 | |||
| e2af298317 | |||
| ab6124ea9b | |||
| b2b670df14 | |||
| 90596b4d0f |
+1
-1
@@ -499,7 +499,7 @@ async function getChatSettings(email) {
|
|||||||
return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) };
|
return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef,
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => J.db, save: () => J.save() }, init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef,
|
||||||
setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, onWalletLinked, count,
|
setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, onWalletLinked, count,
|
||||||
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
|
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
|
||||||
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// Admin action log (Marty 2026-11-16, "a named, logged admin route"): who did what, to what, and when, for admin routes that
|
||||||
|
// change a member's things on their behalf (first user: /api/admin/house-spins). One row per call, denied calls included.
|
||||||
|
// With MySQL (production) the rows live in table admin_audit; without it (local copies, QA) in DATA_DIR/admin-audit.jsonl.
|
||||||
|
// Never holds a secret: callers pass a short summary, and anything that looks like a key or password is masked here too.
|
||||||
|
// record({ who, action, target, ok, detail, ip }) list(limit) -> newest first
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const db = require('./db');
|
||||||
|
|
||||||
|
let DATA_DIR = null, made = false;
|
||||||
|
function init(opts) { DATA_DIR = opts.dataDir; }
|
||||||
|
const FILE = () => path.join(DATA_DIR, 'admin-audit.jsonl');
|
||||||
|
const clip = (s, n) => String(s == null ? '' : s).slice(0, n);
|
||||||
|
// a value under a key like token/secret/password/key never lands in the log
|
||||||
|
const scrub = o => JSON.parse(JSON.stringify(o == null ? null : o, (k, v) => (/pass|secret|token|apikey|api_key|authorization/i.test(k) ? '[masked]' : v)));
|
||||||
|
|
||||||
|
async function table() {
|
||||||
|
if (made) return;
|
||||||
|
await db.q(`CREATE TABLE IF NOT EXISTS admin_audit (
|
||||||
|
id BIGINT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, who VARCHAR(190) NOT NULL, action VARCHAR(80) NOT NULL,
|
||||||
|
target VARCHAR(190) NOT NULL DEFAULT '', ok TINYINT NOT NULL DEFAULT 1, ip VARCHAR(64) NOT NULL DEFAULT '', detail MEDIUMTEXT,
|
||||||
|
KEY ts (ts), KEY action (action)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||||
|
made = true;
|
||||||
|
}
|
||||||
|
async function record(e) {
|
||||||
|
const row = { ts: Date.now(), who: clip(e.who || 'unknown', 190), action: clip(e.action, 80), target: clip(e.target, 190), ok: e.ok === false ? 0 : 1, ip: clip(e.ip, 64), detail: clip(JSON.stringify(scrub(e.detail)), 60000) };
|
||||||
|
try {
|
||||||
|
if (db.enabled()) { await table(); await db.q('INSERT INTO admin_audit (ts, who, action, target, ok, ip, detail) VALUES (?, ?, ?, ?, ?, ?, ?)', [row.ts, row.who, row.action, row.target, row.ok, row.ip, row.detail]); }
|
||||||
|
else fs.appendFileSync(FILE(), JSON.stringify(row) + '\n');
|
||||||
|
return true;
|
||||||
|
} catch (er) { console.error('adminaudit', er.message); return false; }
|
||||||
|
}
|
||||||
|
async function list(limit) {
|
||||||
|
const n = Math.max(1, Math.min(500, Number(limit) || 100));
|
||||||
|
const parse = r => Object.assign({}, r, { ts: Number(r.ts), ok: !!Number(r.ok), detail: (() => { try { return JSON.parse(r.detail); } catch (e) { return r.detail; } })() });
|
||||||
|
if (db.enabled()) { await table(); return (await db.q('SELECT id, ts, who, action, target, ok, ip, detail FROM admin_audit ORDER BY id DESC LIMIT ?', [n])).map(parse); }
|
||||||
|
let lines = []; try { lines = fs.readFileSync(FILE(), 'utf8').split('\n').filter(Boolean); } catch (e) {}
|
||||||
|
return lines.slice(-n).reverse().map(l => { try { return parse(JSON.parse(l)); } catch (e) { return null; } }).filter(Boolean);
|
||||||
|
}
|
||||||
|
module.exports = { init, record, list };
|
||||||
+1
-1
@@ -105,4 +105,4 @@ function matcher(req) { const vid = cookieVid(req), soft = softKey(req); return
|
|||||||
|
|
||||||
// admin Member content (2026-10-18): the audiences members made by hand (every member has an automatic one, not listed)
|
// admin Member content (2026-10-18): the audiences members made by hand (every member has an automatic one, not listed)
|
||||||
function adminAll() { return Object.values(load().audiences).filter(a => !a.auto).map(a => Object.assign({}, a, sizes(a.id))); }
|
function adminAll() { return Object.values(load().audiences).filter(a => !a.auto).map(a => Object.assign({}, a, sizes(a.id))); }
|
||||||
module.exports = { init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: () => load(), _save: () => { save(); flush(); }, init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher };
|
||||||
|
|||||||
@@ -60,7 +60,9 @@ const J = {
|
|||||||
this.sessions.set(token, Object.assign({}, s, fields));
|
this.sessions.set(token, Object.assign({}, s, fields));
|
||||||
this.save();
|
this.save();
|
||||||
},
|
},
|
||||||
async drop(token) { this.sessions.delete(token); this.save(); }
|
async drop(token) { this.sessions.delete(token); this.save(); },
|
||||||
|
async renew(token) { const s = this.sessions.get(token); if (!s) return; s.expires = Date.now() + SESSION_TTL; s.issued = Date.now(); this.save(); },
|
||||||
|
async dropBy(email, address) { let n = 0; for (const [t, s] of this.sessions) if ((email && s.email === email) || (address && String(s.address || '').toLowerCase() === address)) { this.sessions.delete(t); n++; } if (n) this.save(); return n; }
|
||||||
};
|
};
|
||||||
|
|
||||||
// ---- MySQL session mode ----
|
// ---- MySQL session mode ----
|
||||||
@@ -87,7 +89,9 @@ const D = {
|
|||||||
vals.push(token);
|
vals.push(token);
|
||||||
await db.q('UPDATE sessions SET ' + sets.join(',') + ' WHERE token=?', vals);
|
await db.q('UPDATE sessions SET ' + sets.join(',') + ' WHERE token=?', vals);
|
||||||
},
|
},
|
||||||
async drop(token) { await db.q('DELETE FROM sessions WHERE token=?', [token]); }
|
async drop(token) { await db.q('DELETE FROM sessions WHERE token=?', [token]); },
|
||||||
|
async renew(token) { await db.q('UPDATE sessions SET expires=? WHERE token=?', [Date.now() + SESSION_TTL, token]); },
|
||||||
|
async dropBy(email, address) { const r = await db.q('DELETE FROM sessions WHERE ' + (email && address ? 'email=? OR LOWER(address)=?' : email ? 'email=?' : 'LOWER(address)=?'), [email, address].filter(Boolean)); return Number(r.affectedRows || 0); }
|
||||||
};
|
};
|
||||||
const impl = () => db.enabled() ? D : J;
|
const impl = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
@@ -146,7 +150,7 @@ async function verifyChallenge(address, signature) {
|
|||||||
async function mintSession(fields) { return impl().mint(fields || {}); }
|
async function mintSession(fields) { return impl().mint(fields || {}); }
|
||||||
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
||||||
function sessionCookie(token) {
|
function sessionCookie(token) {
|
||||||
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
|
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.max(SESSION_TTL / 1000, 30 * 86400)}${IS_PROD ? '; Secure' : ''}`; // the cookie outlives the session; the server's sliding expiry decides (2026-11-15)
|
||||||
}
|
}
|
||||||
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
||||||
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
||||||
@@ -156,6 +160,9 @@ async function fromRequest(req) {
|
|||||||
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
const s = await impl().get(decodeURIComponent(m[1]));
|
const s = await impl().get(decodeURIComponent(m[1]));
|
||||||
|
// renewed on use (2026-11-15, the network hub era: sessions are SESSION_TTL_HOURS long, 168 = 7 days, and slide while the member
|
||||||
|
// is active; the login ad keeps its own clock, loginadclock.js). At most one write an hour per session.
|
||||||
|
if (s && Number(s.expires) && Number(s.expires) - Date.now() < SESSION_TTL - Math.min(3600000, SESSION_TTL / 4)) { try { await impl().renew(s.token || decodeURIComponent(m[1])); } catch (e) {} }
|
||||||
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
@@ -180,4 +187,5 @@ async function logout(req) {
|
|||||||
if (s) await impl().drop(s.token);
|
if (s) await impl().drop(s.token);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
async function endSessions(email, address) { return impl().dropBy(email ? String(email).toLowerCase() : null, address ? String(address).toLowerCase() : null); } // hub: blocked, erased, signed out everywhere
|
||||||
|
module.exports = { endSessions, init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ function head(o) {
|
|||||||
+ '</head><body><div class="wrap bl">';
|
+ '</head><body><div class="wrap bl">';
|
||||||
}
|
}
|
||||||
function tail() {
|
function tail() {
|
||||||
return '</div><script src="/assets/common.js?v=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
return '</div><script src="/assets/common.js?v=20261117nw"></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>';
|
||||||
|
|||||||
@@ -141,6 +141,113 @@
|
|||||||
"verified": true,
|
"verified": true,
|
||||||
"source": "network"
|
"source": "network"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "videoappincome",
|
||||||
|
"name": "Video App Income",
|
||||||
|
"site": "videoappincome.com",
|
||||||
|
"costModel": "",
|
||||||
|
"params": [
|
||||||
|
{
|
||||||
|
"key": "clickid",
|
||||||
|
"token": "{clickid}",
|
||||||
|
"label": "Click id",
|
||||||
|
"role": "externalId"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"postbackUrl": "",
|
||||||
|
"notes": "Crypto Team Build Network video maker. Clicks that arrive from Video App Income carry ?src=videoappincome and are counted under this source automatically. Sign-ups, sponsor confirmations and credit purchases on Video App Income that follow one of your link clicks are reported back and show under Reports > Conversions.",
|
||||||
|
"verified": true,
|
||||||
|
"source": "network"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "socialtube",
|
||||||
|
"name": "Social Tube",
|
||||||
|
"site": "socialtube.club",
|
||||||
|
"costModel": "",
|
||||||
|
"params": [
|
||||||
|
{
|
||||||
|
"key": "clickid",
|
||||||
|
"token": "{clickid}",
|
||||||
|
"label": "Click id",
|
||||||
|
"role": "externalId"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"postbackUrl": "",
|
||||||
|
"notes": "Crypto Team Build Network video gallery (members' short videos made with Video App Income). Clicks that arrive from Social Tube carry ?src=socialtube and are counted under this source automatically. Sign-ups and credit purchases on Video App Income that follow one of your clicks show in Reports > Conversions.",
|
||||||
|
"verified": true,
|
||||||
|
"source": "network"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "viraladsource",
|
||||||
|
"name": "ViralAdSource",
|
||||||
|
"site": "viraladsource.com",
|
||||||
|
"costModel": "",
|
||||||
|
"params": [
|
||||||
|
{
|
||||||
|
"key": "clickid",
|
||||||
|
"token": "{clickid}",
|
||||||
|
"label": "Click id",
|
||||||
|
"role": "externalId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "placement",
|
||||||
|
"token": "{ad}",
|
||||||
|
"label": "Text ad",
|
||||||
|
"role": "param"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "s1",
|
||||||
|
"token": "{ad}",
|
||||||
|
"label": "Text ad (sub-id)",
|
||||||
|
"role": "param"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"postbackUrl": "",
|
||||||
|
"notes": "Crypto Team Build Network text-ad site. Clicks that arrive from ViralAdSource (its footer, its promo kit) carry ?src=viraladsource and are counted under this source automatically. Your own ViralAdSource text ad goes out as a LinkSpin link on your account: every click carries the ad id as placement and s1.",
|
||||||
|
"verified": true,
|
||||||
|
"source": "network"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "yourprogrambuilder",
|
||||||
|
"name": "YourProgramBuilder",
|
||||||
|
"site": "yourprogrambuilder.com",
|
||||||
|
"costModel": "",
|
||||||
|
"params": [
|
||||||
|
{
|
||||||
|
"key": "clickid",
|
||||||
|
"token": "{clickid}",
|
||||||
|
"label": "Click id",
|
||||||
|
"role": "externalId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "placement",
|
||||||
|
"token": "{packet}",
|
||||||
|
"label": "Program",
|
||||||
|
"role": "param"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "s1",
|
||||||
|
"token": "{packet}",
|
||||||
|
"label": "Program (sub-id)",
|
||||||
|
"role": "param"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"postbackUrl": "",
|
||||||
|
"notes": "Crypto Team Build Network program directory (the Seed Bed). Clicks that arrive from YourProgramBuilder (its footer, its promo kit) carry ?src=yourprogrambuilder and are counted under this source automatically. Your saved referral IDs there go out as LinkSpin links: every click carries the program as placement and s1.",
|
||||||
|
"verified": true,
|
||||||
|
"source": "network"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "5xyourteam",
|
||||||
|
"name": "5xYourTeam",
|
||||||
|
"site": "5xyourteam.com",
|
||||||
|
"costModel": "",
|
||||||
|
"params": [],
|
||||||
|
"postbackUrl": "",
|
||||||
|
"notes": "Crypto Team Build Network team-building site. Clicks that arrive from 5xYourTeam (its footer, its promo kit) carry ?src=fivex and are counted under this source automatically.",
|
||||||
|
"verified": true,
|
||||||
|
"source": "network"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "stackpol",
|
"key": "stackpol",
|
||||||
"name": "Stack POL",
|
"name": "Stack POL",
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
[
|
[
|
||||||
|
{
|
||||||
|
"id": "linkspin-tour",
|
||||||
|
"group": "Start here",
|
||||||
|
"first": true,
|
||||||
|
"title": "How LinkSpin works: the whole site in one walkthrough",
|
||||||
|
"desc": "Start here. A short tour in Marty's voice: what LinkSpin is for (one link that rotates the pages you promote), then step by step: signing in with an email code, making a spin link with weights, a fallback and hours, the Share kit, pointing a link at a traffic source, reading Reports, building a page, adding a zone to your own site, and what ad packages do. Then go on to the Monthly Refuel and Conversion tracking lessons below.",
|
||||||
|
"videoUrl": "https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/linkspin-tour.mp4?v=20261118a",
|
||||||
|
"posterUrl": "https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/linkspin-tour.jpg?v=20261118a"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "banner-spin",
|
"id": "banner-spin",
|
||||||
"group": "Banner Spin",
|
"group": "Banner Spin",
|
||||||
@@ -6,6 +15,16 @@
|
|||||||
"desc": "Banner Spin gives you one image address and one click address that rotate up to 25 banners, each with its own target page or spin link. Put it in one banner slot on a traffic exchange, a safelist, a forum signature or your own site once, then change the banners from your Control Room whenever you like. Nobody has to update anything on their side.\n\nWho gets it. It is a free add-on that opens with your own package of $25 or more. Starter holds 2 Banner Spins with 5 banners each. Builder (level 2 open, 2 qualifying buyers) holds 5 with 15 each. Leader (level 3 open, 5 qualifying buyers) holds 10 with 25 each. If you drop below a tier, everything you built keeps serving; you just cannot add more until you are back.\n\nStep 1, name and size. Open Links, switch to Banner Spins and press New Banner Spin. Pick one size: a slot on an exchange has one size, so every banner in a Banner Spin should be that exact size (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250 or 320x50). Set a fallback page: that is where a click goes when we cannot tell which banner the visitor saw.\n\nStep 2, add banners. Upload a JPG, PNG or GIF (animated is fine, 150 KB at most) or paste an https image address. The builder previews it at real size and warns you when it is the wrong size. Pick where a click goes: any page, or one of your own spin links, so a banner can rotate pages behind it too.\n\nStep 3, weights and mode. A banner with weight 20 shows twice as often as one with 10. Random by weight picks again on every view. One per visitor shows the same person the same banner all day, which keeps a split test clean on exchanges that reload pages. You can also give the whole Banner Spin, or one banner, its own hours.\n\nStep 4, get the code. Open Get the code and copy the embed that fits the place: the image address plus click address for exchanges, safelists and downline builders; the HTML snippet for your own site or blog; the script tag wherever scripts are allowed (it writes the banner and its own link together, so every click lands on the right target); the forum code for signatures. Every link domain answers every code, so if one domain ever has trouble you swap only the domain.\n\nWhere it will not rotate. Paid ad networks copy your image to their own servers when you upload a creative, so it freezes on one banner there: upload real banners to them instead. Gmail and some mail apps fetch images once through their own proxy, so most email readers see one banner and their clicks go to the fallback. For email, use a Banner Spin with a single banner (still tracked) and swap it when you want a change.\n\nReading the numbers. The Stats tab and the Reports screen show views, unique viewers, clicks, click rate, match rate and conversions for every banner and every placement (the page your banner sits on), by day, country and device. Bots, link previews and servers are never counted as views; they are shown on their own line. A WINNER badge appears once two or more live banners have 1,000 views each and one leads on click rate. LinkSpin never changes your weights for you: raise the winner or pause the rest when you are ready. A placement marked CACHED copies banners to its own server, so the rotation is frozen there; spend your credits elsewhere.\n\nHealth checks. Every 30 minutes LinkSpin checks each live banner: the image must load as an image of the right size, and its target must not be dead or parked. Three failures in a row pause that banner and it comes back on its own after two clean checks. The last live banner in a Banner Spin is never paused. You see the status on every banner row.\n\nTeach it forward. When someone in your line buys their first $25 package, show them this lesson and help them build their first Banner Spin with two banners for the same offer. Two weeks of numbers tell them which banner to keep.",
|
"desc": "Banner Spin gives you one image address and one click address that rotate up to 25 banners, each with its own target page or spin link. Put it in one banner slot on a traffic exchange, a safelist, a forum signature or your own site once, then change the banners from your Control Room whenever you like. Nobody has to update anything on their side.\n\nWho gets it. It is a free add-on that opens with your own package of $25 or more. Starter holds 2 Banner Spins with 5 banners each. Builder (level 2 open, 2 qualifying buyers) holds 5 with 15 each. Leader (level 3 open, 5 qualifying buyers) holds 10 with 25 each. If you drop below a tier, everything you built keeps serving; you just cannot add more until you are back.\n\nStep 1, name and size. Open Links, switch to Banner Spins and press New Banner Spin. Pick one size: a slot on an exchange has one size, so every banner in a Banner Spin should be that exact size (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250 or 320x50). Set a fallback page: that is where a click goes when we cannot tell which banner the visitor saw.\n\nStep 2, add banners. Upload a JPG, PNG or GIF (animated is fine, 150 KB at most) or paste an https image address. The builder previews it at real size and warns you when it is the wrong size. Pick where a click goes: any page, or one of your own spin links, so a banner can rotate pages behind it too.\n\nStep 3, weights and mode. A banner with weight 20 shows twice as often as one with 10. Random by weight picks again on every view. One per visitor shows the same person the same banner all day, which keeps a split test clean on exchanges that reload pages. You can also give the whole Banner Spin, or one banner, its own hours.\n\nStep 4, get the code. Open Get the code and copy the embed that fits the place: the image address plus click address for exchanges, safelists and downline builders; the HTML snippet for your own site or blog; the script tag wherever scripts are allowed (it writes the banner and its own link together, so every click lands on the right target); the forum code for signatures. Every link domain answers every code, so if one domain ever has trouble you swap only the domain.\n\nWhere it will not rotate. Paid ad networks copy your image to their own servers when you upload a creative, so it freezes on one banner there: upload real banners to them instead. Gmail and some mail apps fetch images once through their own proxy, so most email readers see one banner and their clicks go to the fallback. For email, use a Banner Spin with a single banner (still tracked) and swap it when you want a change.\n\nReading the numbers. The Stats tab and the Reports screen show views, unique viewers, clicks, click rate, match rate and conversions for every banner and every placement (the page your banner sits on), by day, country and device. Bots, link previews and servers are never counted as views; they are shown on their own line. A WINNER badge appears once two or more live banners have 1,000 views each and one leads on click rate. LinkSpin never changes your weights for you: raise the winner or pause the rest when you are ready. A placement marked CACHED copies banners to its own server, so the rotation is frozen there; spend your credits elsewhere.\n\nHealth checks. Every 30 minutes LinkSpin checks each live banner: the image must load as an image of the right size, and its target must not be dead or parked. Three failures in a row pause that banner and it comes back on its own after two clean checks. The last live banner in a Banner Spin is never paused. You see the status on every banner row.\n\nTeach it forward. When someone in your line buys their first $25 package, show them this lesson and help them build their first Banner Spin with two banners for the same offer. Two weeks of numbers tell them which banner to keep.",
|
||||||
"docUrl": "/links#b"
|
"docUrl": "/links#b"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "video-spin",
|
||||||
|
"group": "Video Spin",
|
||||||
|
"title": "Video Spins: one link, all of your videos",
|
||||||
|
"desc": "A Video Spin is one short link that plays a different video each time it is opened. This lesson shows the whole thing: making one under Links, picking the videos you made on Video App Income, adding any member's video by its Social Tube address, sharing the link, reading each video's clicks, opens, plays and button taps, and putting the rotating player on a web page. Video Spins come with your tier: Starter 2 with 5 videos each, Builder 5 with 15, Leader 10 with 25.",
|
||||||
|
"docUrl": "/links#v",
|
||||||
|
"docLabel": "Open Video Spins",
|
||||||
|
"videoUrl": "https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.mp4?v=20261122a",
|
||||||
|
"posterUrl": "https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.jpg?v=20261122a"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "refuel-guide",
|
"id": "refuel-guide",
|
||||||
"group": "Fuel Your Offers",
|
"group": "Fuel Your Offers",
|
||||||
|
|||||||
+47
-15
File diff suppressed because one or more lines are too long
@@ -299,4 +299,4 @@ function init(opts) { X = arguments[0] || {};
|
|||||||
J.load();
|
J.load();
|
||||||
}
|
}
|
||||||
async function viewsSince(since) { return impl().viewsSince(since); }
|
async function viewsSince(since) { return impl().viewsSince(since); }
|
||||||
module.exports = { init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => J.db, save: () => J.save() }, init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince };
|
||||||
|
|||||||
+1
-1
@@ -315,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 = { 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 };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: () => load(), _save: () => { save(); flush(); }, 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 };
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ async function bootstrap() {
|
|||||||
catch (e) { if (!['ER_DUP_FIELDNAME', 'ER_DUP_KEYNAME'].includes(e.code)) throw e; }
|
catch (e) { if (!['ER_DUP_FIELDNAME', 'ER_DUP_KEYNAME'].includes(e.code)) throw e; }
|
||||||
};
|
};
|
||||||
await alterSafe('ALTER TABLE promo_codes ADD COLUMN funder VARCHAR(190) NULL'); // member-funded partner codes (Nexus), 2026-09-14
|
await alterSafe('ALTER TABLE promo_codes ADD COLUMN funder VARCHAR(190) NULL'); // member-funded partner codes (Nexus), 2026-09-14
|
||||||
|
await alterSafe('ALTER TABLE promo_codes ADD COLUMN starts BIGINT NOT NULL DEFAULT 0'); // 2026-11-17 Network Weekend: a code can open at a set time (0 = open now)
|
||||||
await alterSafe('ALTER TABLE accounts ADD COLUMN username VARCHAR(30) NULL');
|
await alterSafe('ALTER TABLE accounts ADD COLUMN username VARCHAR(30) NULL');
|
||||||
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
|
await alterSafe('ALTER TABLE accounts ADD UNIQUE KEY uq_username (username)');
|
||||||
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
|
await alterSafe('ALTER TABLE accounts ADD COLUMN member_id INT NULL');
|
||||||
|
|||||||
+14
-1
@@ -194,4 +194,17 @@ async function claim(key) {
|
|||||||
// SIGTERM during a deploy: write what is pending, then exit
|
// SIGTERM during a deploy: write what is pending, then exit
|
||||||
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||||
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15)
|
||||||
|
// member erase (2026-11-15): count or delete the rows of a row table whose JSON body has `field` (e.g. '$.r') in `values`. Waits
|
||||||
|
// for queued row writes first, so a click queued before the erase cannot land after it.
|
||||||
|
async function rowsWhere(table, field, values, del) {
|
||||||
|
if (!pool || !values.length) return 0;
|
||||||
|
for (let i = 0; i < 100 && (rowQ.length || rowBusy); i++) await new Promise(r => setTimeout(r, 100));
|
||||||
|
const vals = values.map(String); const where = 'CAST(JSON_UNQUOTE(JSON_EXTRACT(body, ?)) AS CHAR) IN (?)';
|
||||||
|
if (!del) { const [[r]] = await pool.query('SELECT COUNT(*) n FROM `' + table + '` WHERE ' + where, [field, vals]); return Number(r.n); }
|
||||||
|
if (!writer) return 0;
|
||||||
|
const [r] = await pool.query('DELETE FROM `' + table + '` WHERE ' + where, [field, vals]);
|
||||||
|
const mem = ROWS.get(table); if (mem) { const k = field.replace(/^\$\./, ''); ROWS.set(table, mem.filter(x => !vals.includes(String(x[k])))); }
|
||||||
|
return Number(r.affectedRows || 0);
|
||||||
|
}
|
||||||
|
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names, rowsWhere };
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Member erase (Marty 2026-11-15, ticket LS-1021: "I want delete my account data from all your sites"). One named admin action
|
||||||
|
// that takes a person out of LinkSpin from INSIDE the running app, so the documents the modules keep in memory and the MySQL
|
||||||
|
// `docs` rows stay consistent (an edit straight in the database would be written back over by the next save).
|
||||||
|
// POST /api/admin/erase {email, dryRun (default true), force} (admin) and the hub's member.erased event (hubsync.js)
|
||||||
|
// Refused unless force: a linked main wallet, an on-chain member number, linked positions, anyone sponsored under them here,
|
||||||
|
// an ad still running or queued. What goes:
|
||||||
|
// - the account (accounts.removeAccount), their spin links with every click row (rot_hits) and conversion (rotator.eraseOwner);
|
||||||
|
// - every data document that mentions them (scrub.js: their keys, list items and records; another member's record only loses
|
||||||
|
// the pointer), through the owning module's live copy when it keeps one in memory, else read and written through docstore:
|
||||||
|
// accounts, audiences, coach, convtrack, earned (their unspent credits simply go away), hubsync, iapsync, mail-intro,
|
||||||
|
// postbacks, registry, rotator, sponsorfollow, updates-log, and any other document that names them.
|
||||||
|
// Their help-desk tickets live in the shared InstantAdPay desk (InstantAdPay's erase scrubs those). A tombstone (SHA-256 of the
|
||||||
|
// email, kept 30 days in erase.json) stops the InstantAdPay registry sync and hub events from bringing them back while the other
|
||||||
|
// sites catch up. The log keeps hashes and counts, never the email. Dry run = the same counts, nothing changed.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { scrubDeep, scrubText, mentions } = require('./scrub');
|
||||||
|
|
||||||
|
let R = null; // { dataDir, accounts, ads, rotator, docstore, owners: {doc: {state, save}}, reload: {doc: fn}, forget: [fn(email)] }
|
||||||
|
const TOMB_MS = 30 * 86400000;
|
||||||
|
const norm = v => String(v || '').trim().toLowerCase();
|
||||||
|
const hashOf = email => crypto.createHash('sha256').update(norm(email)).digest('hex');
|
||||||
|
const FILE = () => path.join(R.dataDir, 'erase.json');
|
||||||
|
let st = null;
|
||||||
|
function load() {
|
||||||
|
if (st) return st;
|
||||||
|
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||||
|
if (!st || typeof st !== 'object') st = {};
|
||||||
|
st.v = 1; st.tomb = st.tomb || {}; st.log = st.log || [];
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('erase save', e.message); } }
|
||||||
|
function init(deps) { R = deps; st = null; load(); }
|
||||||
|
function isErased(email) {
|
||||||
|
const s = load(); const h = hashOf(email); const t = s.tomb[h];
|
||||||
|
if (!t) return false;
|
||||||
|
if (Date.now() - t > TOMB_MS) { delete s.tomb[h]; save(); return false; }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function docNames() {
|
||||||
|
if (R.docstore && R.docstore.isOn && R.docstore.isOn()) return R.docstore.names();
|
||||||
|
const out = []; const walk = (d, pre) => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) {} for (const x of ents) { const p = path.join(d, x.name); if (x.isDirectory()) walk(p, pre + x.name + '/'); else if (/\.jsonl?$/i.test(x.name)) out.push(pre + x.name); } };
|
||||||
|
walk(R.dataDir, ''); return out;
|
||||||
|
}
|
||||||
|
// every data document that mentions them: counted (dry run) or scrubbed, through the module that holds it in memory if any
|
||||||
|
function docs(needles, dryRun) {
|
||||||
|
const out = {};
|
||||||
|
for (const name of docNames()) {
|
||||||
|
if (name === 'erase.json') continue; // hashes only
|
||||||
|
const file = path.join(R.dataDir, name); let body;
|
||||||
|
try { body = fs.readFileSync(file, 'utf8'); } catch (e) { continue; }
|
||||||
|
if (!mentions(body, needles)) continue;
|
||||||
|
const own = R.owners[name];
|
||||||
|
try {
|
||||||
|
if (own) {
|
||||||
|
const live = own.state(); const n = scrubDeep(dryRun ? JSON.parse(JSON.stringify(live)) : live, needles);
|
||||||
|
if (!dryRun && n) own.save(); out[name] = n;
|
||||||
|
} else {
|
||||||
|
const r = scrubText(body, needles, /\.jsonl$/i.test(name));
|
||||||
|
if (!dryRun && r.removed) { fs.writeFileSync(file, r.body); if (R.reload && R.reload[name]) R.reload[name](); }
|
||||||
|
out[name] = r.removed;
|
||||||
|
}
|
||||||
|
} catch (e) { out[name] = 'error: ' + String(e.message).slice(0, 80); }
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
function docResidue(needles) { return docNames().filter(n => n !== 'erase.json').filter(n => { try { return mentions(fs.readFileSync(path.join(R.dataDir, n), 'utf8'), needles); } catch (e) { return false; } }); }
|
||||||
|
|
||||||
|
async function blockersOf(acct, E) {
|
||||||
|
const out = [];
|
||||||
|
if (acct.address) out.push('main wallet linked');
|
||||||
|
if (Number(acct.memberId) > 0) out.push('on-chain member #' + acct.memberId);
|
||||||
|
try { const pos = await R.accounts.positions(E); if (pos && pos.length) out.push('linked positions: ' + pos.length); } catch (e) {}
|
||||||
|
const refs = [acct.username, acct.code].filter(Boolean).map(norm);
|
||||||
|
if (refs.length) { const team = (await R.accounts.listByReferrer(refs)).filter(a => norm(a.email) !== E); if (team.length) out.push('sponsored under them here: ' + team.length); }
|
||||||
|
try { const live = ((R.ads && await R.ads.listCampaigns(E)) || []).filter(c => ['active', 'queued', 'paused'].includes(c.status)); if (live.length) out.push('ads still running or queued: ' + live.length); } catch (e) {}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// email -> {ok, dryRun, emailHash, found, blockers, account, spinLinks, docs: {doc: removed}, docResidue}
|
||||||
|
async function erase(email, opts) {
|
||||||
|
const o = Object.assign({ dryRun: true, force: false, by: 'admin', sweep: true }, opts || {});
|
||||||
|
const E = norm(email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)) return { error: 'A valid email is required.' };
|
||||||
|
const h = hashOf(E); const acct = await R.accounts.byEmail(E);
|
||||||
|
const exact = acct ? [acct.username, acct.code].filter(Boolean).map(norm) : [];
|
||||||
|
const needles = { emails: [E], exact };
|
||||||
|
const blockers = acct ? await blockersOf(acct, E) : [];
|
||||||
|
const res = { dryRun: !!o.dryRun, emailHash: h, found: !!acct, blockers, forced: !!o.force && blockers.length > 0, account: 0, spinLinks: null, docs: {} };
|
||||||
|
if (blockers.length && !o.force && !o.dryRun) return Object.assign(res, { error: 'Not erased: ' + blockers.join('; ') + '. Send force: true to erase anyway.' });
|
||||||
|
if (!o.dryRun) { load().tomb[h] = Date.now(); save(); } // before anything goes: the syncs refuse them from here on
|
||||||
|
if (acct) { if (o.dryRun) res.account = 1; else { const r = await R.accounts.removeAccount(E); res.account = r && r.ok ? 1 : 0; } }
|
||||||
|
if (R.rotator && R.rotator.eraseOwner) res.spinLinks = await R.rotator.eraseOwner(E, o.dryRun);
|
||||||
|
res.docs = docs(needles, o.dryRun);
|
||||||
|
if (!o.dryRun) for (const f of R.forget || []) { try { f(E); } catch (e) {} } // caches that are not documents (hub lookups, pending pushes)
|
||||||
|
for (const k of Object.keys(res.docs)) if (!res.docs[k]) delete res.docs[k];
|
||||||
|
if (o.sweep) res.docResidue = o.dryRun ? [] : docResidue(needles);
|
||||||
|
if (!o.dryRun) {
|
||||||
|
const s = load(); s.log.push({ at: Date.now(), by: String(o.by).slice(0, 20), hash: h.slice(0, 16), forced: res.forced, found: res.found,
|
||||||
|
spinLinks: res.spinLinks ? res.spinLinks.rotations : 0, docs: Object.keys(res.docs).length, residue: (res.docResidue || []).length });
|
||||||
|
if (s.log.length > 500) s.log = s.log.slice(-500); save();
|
||||||
|
console.log('member erase', h.slice(0, 16), 'by', o.by, 'account', res.account, 'spin links', JSON.stringify(res.spinLinks), 'docs', JSON.stringify(res.docs));
|
||||||
|
}
|
||||||
|
res.ok = true; return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the hub's member.erased event carries only the SHA-256 of the email: find who here has it
|
||||||
|
async function byHash(hash, by) {
|
||||||
|
const h = norm(hash); if (!/^[0-9a-f]{64}$/.test(h)) return { result: 'bad-hash' };
|
||||||
|
let email = null;
|
||||||
|
for (const a of await R.accounts.listAll(1e7, { shells: true })) if (hashOf(a.email) === h) { email = norm(a.email); break; }
|
||||||
|
if (!email) { const s = load(); s.tomb[h] = Date.now(); save(); return { result: 'not-here' }; }
|
||||||
|
const r = await erase(email, { dryRun: false, by: by || 'hub', sweep: false });
|
||||||
|
return { result: r.error ? 'refused' : 'erased', error: r.error || null, docs: r.docs };
|
||||||
|
}
|
||||||
|
function view() { const s = load(); return { tombstones: Object.keys(s.tomb).length, recent: s.log.slice(-20).reverse() }; }
|
||||||
|
|
||||||
|
module.exports = { init, erase, byHash, isErased, hashOf, view, _reset: () => { st = null; } };
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// House Banner Spins (Marty 2026-11-16: "no proper Banner Spins for your house ads"). The admin creates or updates Banner Spins
|
||||||
|
// on a house account (ADMIN_EMAIL or NETWORK_LINKS_OWNER, i.e. Marty's own account) for house ads such as the Network Ad Space
|
||||||
|
// rows, WITHOUT signing in as that member: no member session is read or minted. Every step goes through the same bannerspin.js
|
||||||
|
// calls the member Links screen uses (create, update, addBanner, updateBanner), with the account's email as the owner, so the
|
||||||
|
// checks (sizes, https images and targets, the source belonging to the account, the tier's banner count) are the member's.
|
||||||
|
// server.js wires it as POST /api/admin/house-spins (admin only) and writes every call to the admin action log (adminaudit.js).
|
||||||
|
//
|
||||||
|
// Body: { email, host?, spins: [ { id?, name, size, mode?, fallback?, sourceId?, paused?, prune?,
|
||||||
|
// banners: [ { label, image, target, weight?, active? } ] } ] }
|
||||||
|
// id given -> that Banner Spin (it must belong to the account) is updated; without id, a Banner Spin of the same name and size on
|
||||||
|
// the account is reused, else one is created. Banners match by image address: a match is updated, a new image is
|
||||||
|
// added, and with prune: true a banner whose image is no longer listed is removed.
|
||||||
|
// Reply: { ok, email, host, spins: [ { id, code, name, size, created, added, updated, removed, img, click, errors } ] }
|
||||||
|
'use strict';
|
||||||
|
let R = null; // { bannerspin, houseAccounts(): [email], host(wanted): the link domain (wanted when it is one of ours, else the first) }
|
||||||
|
function init(refs) { R = refs; }
|
||||||
|
const norm = e => String(e || '').trim().toLowerCase();
|
||||||
|
|
||||||
|
async function apply(body) {
|
||||||
|
const email = norm(body && body.email);
|
||||||
|
if (!email) return { error: 'Which account? Pass email.' };
|
||||||
|
if (!R.houseAccounts().includes(email)) return { error: 'House Banner Spins go on a house account only (the admin account).' };
|
||||||
|
const list = Array.isArray(body.spins) ? body.spins : [];
|
||||||
|
if (!list.length || list.length > 40) return { error: 'Pass 1 to 40 spins.' };
|
||||||
|
const BS = R.bannerspin; const host = R.host(body.host); const out = [];
|
||||||
|
for (const want of list) {
|
||||||
|
const row = { name: String(want.name || ''), size: String(want.size || ''), created: false, added: 0, updated: 0, removed: 0, errors: [] };
|
||||||
|
out.push(row);
|
||||||
|
let spin = null;
|
||||||
|
const mine = await BS.list(email);
|
||||||
|
if (want.id != null) { spin = mine.find(s => s.id === Number(want.id)) || null; if (!spin) { row.errors.push('No Banner Spin ' + want.id + ' on this account.'); continue; } }
|
||||||
|
else spin = mine.find(s => s.name === String(want.name || '').trim() && s.size === row.size) || null;
|
||||||
|
if (!spin) {
|
||||||
|
const r = await BS.create(email, { name: want.name, size: want.size, mode: want.mode, fallback: want.fallback });
|
||||||
|
if (r.error) { row.errors.push(r.error); continue; }
|
||||||
|
spin = r.spin; row.created = true;
|
||||||
|
}
|
||||||
|
const patch = {};
|
||||||
|
if (want.name != null && String(want.name).trim() !== spin.name) patch.name = want.name;
|
||||||
|
if (want.mode != null) patch.mode = want.mode;
|
||||||
|
if (want.fallback != null) patch.fallback = want.fallback;
|
||||||
|
if (want.sourceId != null) patch.sourceId = want.sourceId;
|
||||||
|
if (want.paused != null) patch.paused = !!want.paused;
|
||||||
|
if (Object.keys(patch).length) { const r = await BS.update(email, spin.id, patch); if (r.error) row.errors.push(r.error); else spin = r.spin; }
|
||||||
|
const banners = Array.isArray(want.banners) ? want.banners : [];
|
||||||
|
for (const b of banners) {
|
||||||
|
const have = spin.banners.find(x => x.image === String(b.image || '').trim());
|
||||||
|
if (have) {
|
||||||
|
const p = {}; if (b.label != null && b.label !== have.label) p.label = b.label; if (b.weight != null && Number(b.weight) !== have.weight) p.weight = b.weight;
|
||||||
|
if (b.target != null && b.target !== have.target) p.target = b.target; const act = b.active == null ? true : !!b.active; if (act !== have.active) p.active = act;
|
||||||
|
if (Object.keys(p).length) { const r = await BS.updateBanner(email, spin.id, have.id, p); if (r.error) row.errors.push(have.id + ': ' + r.error); else { spin = r.spin; row.updated++; } }
|
||||||
|
} else {
|
||||||
|
const r = await BS.addBanner(email, spin.id, { label: b.label, image: b.image, target: b.target, weight: b.weight });
|
||||||
|
if (r.error) row.errors.push(String(b.image).slice(0, 80) + ': ' + r.error); else { spin = r.spin; row.added++; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (want.prune) {
|
||||||
|
const keep = new Set(banners.map(b => String(b.image || '').trim()));
|
||||||
|
for (const x of spin.banners.filter(x => !keep.has(x.image))) { const r = await BS.updateBanner(email, spin.id, x.id, { remove: true }); if (r.error) row.errors.push(x.id + ': ' + r.error); else { spin = r.spin; row.removed++; } }
|
||||||
|
}
|
||||||
|
Object.assign(row, { id: spin.id, code: spin.code, name: spin.name, size: spin.size, sourceId: spin.sourceId || '', fallback: spin.fallback || '', banners: spin.banners.length,
|
||||||
|
img: 'https://' + host + '/i/' + spin.code + '.gif', click: 'https://' + host + '/c/' + spin.code });
|
||||||
|
}
|
||||||
|
return { ok: out.every(r => !r.errors.length), email, host, spins: out };
|
||||||
|
}
|
||||||
|
module.exports = { init, apply };
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// The network AI ad writer, asked through the hub (Marty 2026-11-17: "the AI generation of the ads worked really well. Let's go
|
||||||
|
// ahead and do it on the other sites too."). The hub reads the member's page, asks the model and filters the copy
|
||||||
|
// (network-hub lib/adwriter.js); this file only signs the call for this site's signed-in member and passes the answer on.
|
||||||
|
// status(member?) -> {on, daily, left?} (cached 60 s; on: false when the hub is unset, unreachable or switched off)
|
||||||
|
// write(member, url, limits) -> {ok, options: [{headline, line?}], url, cached, left} | {error (member-friendly), code, status, left?}
|
||||||
|
// Signed as HUB_SITE with HUB_SECRET: X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body), like every /v1 call.
|
||||||
|
// AI_WRITER=0 hides the button on this site. Nothing is posted: the member picks an option, edits it and saves it themselves.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const DEFAULT_SITE = 'linkspin';
|
||||||
|
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const site = () => String(process.env.HUB_SITE || DEFAULT_SITE).trim();
|
||||||
|
const configured = () => !/^(0|false|no|off)$/i.test(String(process.env.AI_WRITER || '').trim()) && !!hubUrl() && secret().length >= 32;
|
||||||
|
|
||||||
|
async function call(route, body, timeoutMs) {
|
||||||
|
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||||
|
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(hubUrl() + route, { method: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
|
||||||
|
let j = null; try { j = await r.json(); } catch (e) { j = null; }
|
||||||
|
return { status: r.status, body: j || {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
let st = { at: 0, v: { on: false, daily: 0 } };
|
||||||
|
async function status(member) {
|
||||||
|
if (!configured()) return { on: false, daily: 0 };
|
||||||
|
if (!member && Date.now() - st.at < 60000) return st.v;
|
||||||
|
try {
|
||||||
|
const r = await call('/v1/adwriter/status', member ? { member: String(member) } : {}, 3000);
|
||||||
|
const v = r.status === 200 && r.body && typeof r.body.on === 'boolean' ? r.body : { on: false, daily: 0 };
|
||||||
|
if (!member) st = { at: Date.now(), v: { on: v.on, daily: v.daily || 0 } };
|
||||||
|
return v;
|
||||||
|
} catch (e) { if (!member) st = { at: Date.now() - 45000, v: { on: false, daily: 0 } }; return { on: false, daily: 0 }; } // a down hub is asked again in 15 s
|
||||||
|
}
|
||||||
|
// the button shows only when the hub says the writer is on (60 s cache, never waits on a slow hub for long)
|
||||||
|
async function enabled() { return (await status()).on === true; }
|
||||||
|
|
||||||
|
async function write(member, url, limits) {
|
||||||
|
if (!configured()) return { error: 'The ad writer is switched off right now. You can still write your ad yourself.', code: 'off', status: 503 };
|
||||||
|
try {
|
||||||
|
const r = await call('/v1/adwriter', { member: String(member), url: String(url || '').trim().slice(0, 600), limits }, 75000);
|
||||||
|
const b = r.body || {};
|
||||||
|
if (r.status === 200 && b.ok && Array.isArray(b.options)) return { ok: true, options: b.options, url: b.url, cached: !!b.cached, left: b.left };
|
||||||
|
if (r.status === 401 || r.status === 403 || !b.message) { console.error('hubadwriter: hub answered ' + r.status + ' ' + String(b.error || '')); return { error: 'The ad writer is busy right now. Try again in a minute, or write your ad yourself.', code: 'hub', status: 502 }; }
|
||||||
|
return { error: String(b.message), code: b.error || b.code || 'error', status: r.status >= 400 && r.status < 600 ? r.status : 502, left: b.left };
|
||||||
|
} catch (e) {
|
||||||
|
console.error('hubadwriter: ' + (e.name === 'TimeoutError' || e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120)));
|
||||||
|
return { error: 'The ad writer did not answer in time. Try again in a minute, or write your ad yourself.', code: 'hub', status: 504 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { status, enabled, write, configured, _reset: () => { st = { at: 0, v: { on: false, daily: 0 } }; } };
|
||||||
+11
-1
@@ -3,6 +3,7 @@
|
|||||||
// IN POST /api/hub/events body {events:[{seq, at, type, personId, data}]}, headers X-Hub-Ts (ms) + X-Hub-Sig = hex
|
// 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
|
// 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).
|
// only moves its cursor on a 2xx, so events can arrive twice: each seq is applied once (DATA_DIR/hubsync.json lastSeq).
|
||||||
|
// member.erased (2026-11-15): the hub erased someone; erase.js finds them by the SHA-256 of the email and takes them out.
|
||||||
// member.joined from another door: /v1/resolve {id} for the person, then the SAME waiting (shell) account the InstantAdPay
|
// 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
|
// 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
|
// EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed
|
||||||
@@ -81,6 +82,7 @@ const quiet = new Set(); const isQuiet = email => quiet.has(norm(email));
|
|||||||
// QUIET (Marty 2026-11-14, "join one = join all"): nothing here sends mail, a notice or a post; qa/hubsync.test.cjs checks it.
|
// QUIET (Marty 2026-11-14, "join one = join all"): nothing here sends mail, a notice or a post; qa/hubsync.test.cjs checks it.
|
||||||
async function place(p, depth, seen) {
|
async function place(p, depth, seen) {
|
||||||
const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e);
|
const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e);
|
||||||
|
if (R.erased && R.erased(e)) return null; // erased here (erase.js, 2026-11-15): a hub event never brings them back
|
||||||
const ps = sponsorFor(p);
|
const ps = sponsorFor(p);
|
||||||
let sp = ps && ps.email ? await R.accounts.byEmail(ps.email) : null;
|
let sp = ps && ps.email ? await R.accounts.byEmail(ps.email) : null;
|
||||||
if (!sp && ps && ps.id && depth < MAX_UP) { // the sponsor is new here too: their line first
|
if (!sp && ps && ps.id && depth < MAX_UP) { // the sponsor is new here too: their line first
|
||||||
@@ -117,6 +119,14 @@ async function apply(ev) {
|
|||||||
if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back
|
if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back
|
||||||
const p = await resolveId(ev.personId);
|
const p = await resolveId(ev.personId);
|
||||||
if (p && p.email) await place(p, 0, new Set());
|
if (p && p.email) await place(p, 0, new Set());
|
||||||
|
} else if (type === 'member.erased') { // the hub erased someone (2026-11-15): erase.js finds them by the SHA-256 of the email
|
||||||
|
if (!R.erase) return;
|
||||||
|
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
|
||||||
|
if (r.result === 'refused') console.error('hubsync member.erased refused here:', String(r.error || '').slice(0, 200));
|
||||||
|
} else if (type === 'member.blocked' || type === 'member.signedout') { // network sign-in (2026-11-15): blocked, or "Sign out everywhere" on any site
|
||||||
|
if (!R.endSessions) return;
|
||||||
|
const p = await resolveId(ev.personId); if (!p || !p.email) return;
|
||||||
|
await R.endSessions(p.email, p.wallet || null);
|
||||||
} else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync
|
} 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 p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return;
|
||||||
const a = await R.accounts.byEmail(p.email);
|
const a = await R.accounts.byEmail(p.email);
|
||||||
@@ -329,4 +339,4 @@ function adminView() {
|
|||||||
made: Object.keys(st.made || {}).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null,
|
made: Object.keys(st.made || {}).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || 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 };
|
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, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: load, _save: save, _forgetHeld: e => held.delete(norm(e)), init, on, receive, touch, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
||||||
|
|||||||
+1
-1
@@ -143,4 +143,4 @@ async function tick(force) {
|
|||||||
finally { ticking = false; }
|
finally { ticking = false; }
|
||||||
}
|
}
|
||||||
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, knownSkipped: st.known, last: st.last, errors: st.errors, lastError: st.lastError || null, pendingTouches: pending.size }; }
|
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, knownSkipped: st.known, last: st.last, errors: st.errors, lastError: st.lastError || null, pendingTouches: pending.size }; }
|
||||||
module.exports = { init, touch, tick, adminView, on };
|
module.exports = { init, touch, tick, adminView, on, /* member erase (erase.js, 2026-11-15): the live copy */ _state: load, _save: save, _forget: e => pending.delete(norm(e)) };
|
||||||
|
|||||||
+1
-1
@@ -32,7 +32,7 @@ const FAQ = [
|
|||||||
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
||||||
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
||||||
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
||||||
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' },
|
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside your wallet app, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' },
|
||||||
{ id: 'f-payouts-where', title: 'Where do my payouts go?', source: 'faq',
|
{ id: 'f-payouts-where', title: 'Where do my payouts go?', source: 'faq',
|
||||||
questions: ['Where do my payouts go?', 'Which wallet gets paid?', 'Does the site hold my earnings?'],
|
questions: ['Where do my payouts go?', 'Which wallet gets paid?', 'Does the site hold my earnings?'],
|
||||||
tags: ['payout', 'wallet', 'custody'],
|
tags: ['payout', 'wallet', 'custody'],
|
||||||
|
|||||||
@@ -9,6 +9,12 @@
|
|||||||
// path serves the new text.
|
// path serves the new text.
|
||||||
// source canned | faq | ticket | admin
|
// source canned | faq | ticket | admin
|
||||||
//
|
//
|
||||||
|
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's own
|
||||||
|
// entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries (NAMED_BOOST) and
|
||||||
|
// skips this site's instant answers (namesOther, chatbot.js). Other sites' entries never take the fast path; they ride along as
|
||||||
|
// context labelled with the site and the link to send people to. This site's own entries are published to the hub. The same
|
||||||
|
// merge code is in InstantAdPay, LinkSpin and the rebuilt sites' kb.js.
|
||||||
|
//
|
||||||
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||||
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||||
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||||
@@ -22,10 +28,11 @@
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
|
||||||
const { SITE_URL } = require('./host');
|
const { SITE_URL } = require('./host');
|
||||||
|
|
||||||
let DATA_DIR = null, SEEDS = [], ready = null;
|
let DATA_DIR = null, SEEDS = [], ready = null;
|
||||||
let cache = null, cacheAt = 0, index = null;
|
let cache = null, cacheAt = 0, index = null, netVer = '';
|
||||||
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
|
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
|
||||||
|
|
||||||
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||||
@@ -82,10 +89,38 @@ function buildIndex(entries) {
|
|||||||
}
|
}
|
||||||
return { docs, df, avg, n: docs.length };
|
return { docs, df, avg, n: docs.length };
|
||||||
}
|
}
|
||||||
|
const HOME_BOOST = 2, NAMED_BOOST = 3;
|
||||||
|
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
|
||||||
|
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
|
||||||
|
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
|
||||||
|
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
|
||||||
|
function namedSites(query, idx) {
|
||||||
|
const q = norm(query); const out = new Set();
|
||||||
|
for (const s of (idx && idx.sites) || []) {
|
||||||
|
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
|
||||||
|
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside.
|
||||||
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
|
||||||
|
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
|
||||||
|
function namesOther(query, self) {
|
||||||
|
const q = norm(query); const out = [];
|
||||||
|
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
|
||||||
|
for (const id of ids) {
|
||||||
|
if (id === self) continue;
|
||||||
|
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
|
||||||
|
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
|
||||||
|
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
function rank(idx, query, k) {
|
function rank(idx, query, k) {
|
||||||
if (!idx || !idx.n) return [];
|
if (!idx || !idx.n) return [];
|
||||||
const qt = [...new Set(terms(query))];
|
const qt = [...new Set(terms(query))];
|
||||||
if (!qt.length) return [];
|
if (!qt.length) return [];
|
||||||
|
const named = namedSites(query, idx);
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const d of idx.docs) {
|
for (const d of idx.docs) {
|
||||||
let s = 0;
|
let s = 0;
|
||||||
@@ -97,6 +132,8 @@ function rank(idx, query, k) {
|
|||||||
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (s > 0 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
|
||||||
|
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
|
||||||
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||||
}
|
}
|
||||||
out.sort((a, b) => b.score - a.score);
|
out.sort((a, b) => b.score - a.score);
|
||||||
@@ -153,9 +190,10 @@ function init(opts) {
|
|||||||
}
|
}
|
||||||
async function load(force) {
|
async function load(force) {
|
||||||
if (ready) await ready;
|
if (ready) await ready;
|
||||||
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
|
if (!force && cache && Date.now() - cacheAt < TTL && (!netkb || netkb.version() === netVer)) return cache; // a new network set rebuilds at once
|
||||||
const all = await store().all();
|
const all = await store().all();
|
||||||
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
|
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear(); netVer = netkb ? netkb.version() : '';
|
||||||
|
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
|
||||||
return cache;
|
return cache;
|
||||||
}
|
}
|
||||||
const rx = new Map();
|
const rx = new Map();
|
||||||
@@ -173,13 +211,16 @@ async function fastPath(msg) {
|
|||||||
}
|
}
|
||||||
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||||
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
||||||
|
// this site's own entries, for netkb.publish
|
||||||
|
async function own() { await load(); return cache.slice(); }
|
||||||
|
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
|
||||||
const HELP = 'Help (' + SITE_URL + '/help, or ' + SITE_URL + '/support when signed out)';
|
const HELP = 'Help (' + SITE_URL + '/help, or ' + SITE_URL + '/support when signed out)';
|
||||||
function promptBlock(hits) {
|
function promptBlock(hits) {
|
||||||
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
||||||
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||||
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||||
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||||
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + label(h.entry) + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- the admin side
|
// ---------------------------------------------------------------- the admin side
|
||||||
@@ -200,7 +241,7 @@ function validate(o, cur) {
|
|||||||
async function list(q) {
|
async function list(q) {
|
||||||
const all = (await load(true)).slice();
|
const all = (await load(true)).slice();
|
||||||
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||||
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
|
const ranked = rank(index, q, 50).filter(h => !h.entry.site).map(h => Object.assign({ score: h.score }, h.entry));
|
||||||
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||||
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||||
return ranked.concat(plain);
|
return ranked.concat(plain);
|
||||||
@@ -211,19 +252,19 @@ async function create(o) {
|
|||||||
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||||
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||||
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||||
await store().put(e); await load(true);
|
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true, entry: e };
|
return { ok: true, entry: e };
|
||||||
}
|
}
|
||||||
async function update(id, o) {
|
async function update(id, o) {
|
||||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
const v = validate(o, cur); if (v.error) return v;
|
const v = validate(o, cur); if (v.error) return v;
|
||||||
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||||
await store().put(e); await load(true);
|
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true, entry: e };
|
return { ok: true, entry: e };
|
||||||
}
|
}
|
||||||
async function remove(id) {
|
async function remove(id) {
|
||||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
|
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); if (netkb) netkb.publishSoon();
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||||
@@ -238,8 +279,8 @@ async function stamp() {
|
|||||||
async function test(question) {
|
async function test(question) {
|
||||||
const fast = await fastPath(String(question || ''));
|
const fast = await fastPath(String(question || ''));
|
||||||
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||||
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
module.exports = { init, load, own, namesOther, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||||
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
|
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };
|
||||||
|
|||||||
+1
-1
@@ -146,7 +146,7 @@ async function renderPage() {
|
|||||||
const w = winners();
|
const w = winners();
|
||||||
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
||||||
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Weekly and monthly 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=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261117nw"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
function setLaunchPanel(fn) { if (R) R.launchPanel = fn; }
|
function setLaunchPanel(fn) { if (R) R.launchPanel = fn; }
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Login-ad clock (Marty 2026-11-15): "I definitely don't want somebody to not look at a login ad for 7 days... if login ads are
|
||||||
|
// available on those sites, they need to be seen several times a day." The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
//
|
||||||
|
// A member sees the login ad on their next member-area page load whenever their last finished login-ad view on THIS site is more
|
||||||
|
// than loginAdEveryHours old (site setting, default 3), whether or not they just signed in. One row per member in MySQL
|
||||||
|
// (table login_ad_views: k = lowercased email, or 'w:' + wallet for a wallet-only session; seen_at; served_at).
|
||||||
|
// due(k) true when the member should get the login ad now (no row, or seen_at older than the setting)
|
||||||
|
// served(k) the login ad was handed to this member (the countdown starts on their screen)
|
||||||
|
// seen(k, s) the countdown ended: counts only when a serve to this member happened at least s - 2 seconds ago and within the
|
||||||
|
// last 30 minutes, so reloading during the countdown never skips the ad
|
||||||
|
// forget(k) member erase
|
||||||
|
// No database (local QA): the same rules in memory. A failed database read answers "due": when in doubt the ad shows.
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
let pool = null, tableReady = null, hours = () => 3;
|
||||||
|
const mem = new Map(); // k -> { seen, served }
|
||||||
|
const SERVE_WINDOW = 30 * 60 * 1000;
|
||||||
|
|
||||||
|
const keyOf = s => {
|
||||||
|
if (!s) return '';
|
||||||
|
const e = String(s.email || '').trim().toLowerCase();
|
||||||
|
if (e) return e.slice(0, 190);
|
||||||
|
const a = String(s.address || '').trim().toLowerCase();
|
||||||
|
return /^0x[0-9a-f]{40}$/.test(a) ? 'w:' + a : '';
|
||||||
|
};
|
||||||
|
const everyMs = () => { const h = Number(hours()); return (Number.isFinite(h) && h > 0 ? Math.min(h, 24 * 30) : 3) * 3600 * 1000; };
|
||||||
|
|
||||||
|
function init(opts) {
|
||||||
|
const o = opts || {};
|
||||||
|
if (typeof o.hours === 'function') hours = o.hours;
|
||||||
|
const url = String(o.url || '').trim();
|
||||||
|
pool = null; tableReady = null; mem.clear();
|
||||||
|
if (url) { const mysql = require('mysql2/promise'); pool = mysql.createPool({ uri: url, connectionLimit: 3, charset: 'utf8mb4' }); }
|
||||||
|
}
|
||||||
|
async function table() {
|
||||||
|
if (!tableReady) tableReady = pool.query('CREATE TABLE IF NOT EXISTS login_ad_views (k VARCHAR(200) PRIMARY KEY, seen_at BIGINT NOT NULL DEFAULT 0, served_at BIGINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').catch(e => { tableReady = null; throw e; });
|
||||||
|
return tableReady;
|
||||||
|
}
|
||||||
|
async function row(k) {
|
||||||
|
if (!pool) return mem.get(k) || null;
|
||||||
|
await table();
|
||||||
|
const [r] = await pool.query('SELECT seen_at, served_at FROM login_ad_views WHERE k = ?', [k]);
|
||||||
|
return r[0] ? { seen: Number(r[0].seen_at) || 0, served: Number(r[0].served_at) || 0 } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function due(k, now) {
|
||||||
|
if (!k) return false;
|
||||||
|
const t = now || Date.now();
|
||||||
|
try { const r = await row(k); return !r || !r.seen || t - r.seen >= everyMs(); } catch (e) { console.error('login-ad clock read', e.message); return true; }
|
||||||
|
}
|
||||||
|
async function served(k, now) {
|
||||||
|
if (!k) return;
|
||||||
|
const t = now || Date.now();
|
||||||
|
if (!pool) { const r = mem.get(k) || { seen: 0, served: 0 }; r.served = t; mem.set(k, r); return; }
|
||||||
|
try { await table(); await pool.query('INSERT INTO login_ad_views (k, served_at) VALUES (?, ?) ON DUPLICATE KEY UPDATE served_at = VALUES(served_at)', [k, t]); }
|
||||||
|
catch (e) { console.error('login-ad clock serve', e.message); }
|
||||||
|
}
|
||||||
|
// -> { ok: true } or { ok: false, reason }
|
||||||
|
async function seen(k, dwellSec, now) {
|
||||||
|
if (!k) return { ok: false, reason: 'signed out' };
|
||||||
|
const t = now || Date.now();
|
||||||
|
const need = Math.max(0, (Number(dwellSec) || 10) - 2) * 1000;
|
||||||
|
let r = null; try { r = await row(k); } catch (e) { console.error('login-ad clock read', e.message); return { ok: false, reason: 'store' }; }
|
||||||
|
if (!r || !r.served || t - r.served > SERVE_WINDOW) return { ok: false, reason: 'not served' };
|
||||||
|
if (t - r.served < need) return { ok: false, reason: 'too soon' };
|
||||||
|
if (!pool) { r.seen = t; mem.set(k, r); return { ok: true }; }
|
||||||
|
try { await pool.query('UPDATE login_ad_views SET seen_at = ? WHERE k = ?', [t, k]); return { ok: true }; }
|
||||||
|
catch (e) { console.error('login-ad clock seen', e.message); return { ok: false, reason: 'store' }; }
|
||||||
|
}
|
||||||
|
async function forget(k) {
|
||||||
|
if (!k) return;
|
||||||
|
mem.delete(k);
|
||||||
|
if (pool) { try { await table(); await pool.query('DELETE FROM login_ad_views WHERE k = ?', [k]); } catch (e) { console.error('login-ad clock forget', e.message); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, keyOf, due, served, seen, forget, everyMs };
|
||||||
@@ -77,4 +77,4 @@ function sendCode(to, code) {
|
|||||||
+ 'LinkSpin\nAdvertise and earn instantly. Locked in code, not promises.\n' + SITE_URL, { code: true });
|
+ 'LinkSpin\nAdvertise and earn instantly. Locked in code, not promises.\n' + SITE_URL, { code: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, hasKey, send, sendCode };
|
module.exports = { init, hasKey, send, sendCode, /* member erase (erase.js, 2026-11-15): the live copy */ _intro: { state: () => introLoad(), save: () => { try { fs.writeFileSync(introFile() + '.tmp', JSON.stringify(introLoad())); fs.renameSync(introFile() + '.tmp', introFile()); } catch (e) {} } } };
|
||||||
|
|||||||
+4
-2
@@ -19,6 +19,7 @@ const path = require('path');
|
|||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
|
||||||
const EVENTS = ['join', 'wallet', 'purchase'];
|
const EVENTS = ['join', 'wallet', 'purchase'];
|
||||||
|
const SITE_NAMES = { vai: 'Video App Income' }; // events reported by another network site carry its id; none = InstantAdPay
|
||||||
let FILE = null, C = null, R = null, B = null, P = null, M = null;
|
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() };
|
let st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() };
|
||||||
const norm = e => String(e || '').trim().toLowerCase();
|
const norm = e => String(e || '').trim().toLowerCase();
|
||||||
@@ -72,11 +73,12 @@ async function record(e) {
|
|||||||
const value = ev === 'purchase' ? C.cleanValue(e.value) : 0;
|
const value = ev === 'purchase' ? C.cleanValue(e.value) : 0;
|
||||||
const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : '';
|
const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : '';
|
||||||
const tx = String(e.tx || '').slice(0, 80) || undefined;
|
const tx = String(e.tx || '').slice(0, 80) || undefined;
|
||||||
|
const site = SITE_NAMES[String(e.site || '')] ? String(e.site) : undefined;
|
||||||
const rows = owners.map(o => {
|
const rows = owners.map(o => {
|
||||||
const was = (prior || []).find(r => r.owner === 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 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 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);
|
const row = Object.assign({ k: owners.length > 1 ? k + '|' + o : k, ev, ts: at, rec: now, value, acct, click, root, clickTs, owner: o, tx, site, self: self ? 1 : undefined }, f);
|
||||||
for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x];
|
for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x];
|
||||||
return row;
|
return row;
|
||||||
});
|
});
|
||||||
@@ -100,7 +102,7 @@ async function fromLinkSpin(lsid, ev, facts) {
|
|||||||
}
|
}
|
||||||
async function mirror(r) {
|
async function mirror(r) {
|
||||||
const key = r.k.split('|')[0];
|
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.rot) return R.convert(r.click, r.ev, { payout: r.value, label: r.ev === 'purchase' ? (SITE_NAMES[r.site] || '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 });
|
if (r.kind === 'bspin' && r.click[0] === 'k') return R.convert(r.click, r.ev, { payout: r.value, key, ts: r.ts });
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
// Network deals for this site's "Network Weekend" ribbon (Marty 2026-11-17). One source: the hub's public GET /v1/network-deals
|
||||||
|
// (HUB_URL). Cached 2 minutes, refreshed in the background, never waits on a slow hub (2.5 s timeout); hub down = no ribbon.
|
||||||
|
// The same file lives in every network site. Never RM Circle, never the games (the hub list never names them).
|
||||||
|
// The page (/assets/netweekend.js) switches the ribbon on and off by its own clock at startsAt / endsAt, so a cached copy never
|
||||||
|
// shows early or late. setLocal(fn) lets a site rewrite its own deal line from live data (for example a price read from chain),
|
||||||
|
// so the ribbon never shows a number the contract does not charge: fn(deal) returns the deal, a changed copy, or null to drop it.
|
||||||
|
const TTL = 2 * 60 * 1000;
|
||||||
|
let cache = { at: 0, body: { events: [] } };
|
||||||
|
let inflight = null;
|
||||||
|
let local = null;
|
||||||
|
|
||||||
|
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||||
|
const safeUrl = u => (/^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(u || '')) ? String(u) : '');
|
||||||
|
const str = (v, n) => String(v == null ? '' : v).slice(0, n || 300);
|
||||||
|
function clean(j) {
|
||||||
|
if (!j || !Array.isArray(j.events)) return null;
|
||||||
|
return { events: j.events.slice(0, 5).filter(e => e && e.id && !Number.isNaN(Date.parse(e.startsAt)) && !Number.isNaN(Date.parse(e.endsAt))).map(e => ({
|
||||||
|
id: str(e.id, 60), name: str(e.name, 60), tagline: str(e.tagline, 160), url: safeUrl(e.url), startsAt: e.startsAt, endsAt: e.endsAt,
|
||||||
|
days: e.days && typeof e.days === 'object' ? Object.fromEntries(Object.entries(e.days).slice(0, 20).map(([k, v]) => [str(k, 10), str(v, 40)])) : {},
|
||||||
|
deals: (Array.isArray(e.deals) ? e.deals : []).slice(0, 40).map(d => {
|
||||||
|
const x = { site: str(d.site, 30), name: str(d.name, 80), url: safeUrl(d.url), text: str(d.text), endsAt: Number.isNaN(Date.parse(d.endsAt)) ? e.endsAt : d.endsAt };
|
||||||
|
if (d.note) x.note = str(d.note, 120);
|
||||||
|
if (d.byDay && typeof d.byDay === 'object') x.byDay = Object.fromEntries(Object.entries(d.byDay).slice(0, 20).map(([k, v]) => [str(k, 10), str(v)]));
|
||||||
|
return x;
|
||||||
|
})
|
||||||
|
})) };
|
||||||
|
}
|
||||||
|
function refresh() {
|
||||||
|
if (inflight || process.env.NETWORK_DEALS_HUB === '0') return inflight;
|
||||||
|
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||||
|
inflight = fetch(hubUrl() + '/v1/network-deals', { signal: ac.signal })
|
||||||
|
.then(r => (r.ok ? r.json() : null))
|
||||||
|
.then(j => { const b = clean(j); if (b) cache = { at: Date.now(), body: b }; else cache.at = Date.now(); })
|
||||||
|
.catch(() => { cache.at = Date.now() - TTL + 30 * 1000; }) // hub down: try again in 30 s, keep the last good copy
|
||||||
|
.finally(() => { clearTimeout(t); inflight = null; });
|
||||||
|
return inflight;
|
||||||
|
}
|
||||||
|
function current() { if (Date.now() - cache.at > TTL) refresh(); return cache.body; }
|
||||||
|
function setLocal(fn) { local = typeof fn === 'function' ? fn : null; }
|
||||||
|
function withLocal(body, self) {
|
||||||
|
if (!local) return body;
|
||||||
|
return { events: body.events.map(e => Object.assign({}, e, { deals: e.deals.map(d => {
|
||||||
|
if (d.site !== self) return d;
|
||||||
|
try { const r = local(Object.assign({}, d)); return r === undefined ? d : r; } catch (err) { return d; }
|
||||||
|
}).filter(Boolean) })) };
|
||||||
|
}
|
||||||
|
// GET /api/network-deals: public, short cache, the same answer on every page. self = this site's network id (NETWORK_SITE_ID).
|
||||||
|
function handle(req, res, self) {
|
||||||
|
const me = String(self || process.env.NETWORK_SITE_ID || '').trim().toLowerCase();
|
||||||
|
const body = Object.assign({ self: me }, withLocal(current(), me));
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=60', 'X-Content-Type-Options': 'nosniff' });
|
||||||
|
res.end(JSON.stringify(body));
|
||||||
|
}
|
||||||
|
module.exports = { current, handle, refresh, setLocal, clean, _set: b => { cache = { at: Date.now(), body: clean(b) || { events: [] } }; } };
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
|
||||||
|
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
|
||||||
|
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
|
||||||
|
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
|
||||||
|
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
|
||||||
|
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||||
|
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||||
|
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||||
|
//
|
||||||
|
// SEMANTIC MATCHING (Marty 2026-11-16): the hub matches a question by meaning against the whole network KB with the free core2
|
||||||
|
// embeddings model (POST HUB_URL/v1/kb/match). match() asks it with a strict timeout (NETKB_MATCH_MS, default 1500) and fails
|
||||||
|
// soft: an error or a timeout answers null and the next MATCH_PAUSE_MS skip the hub, so the chat never waits on a slow model and
|
||||||
|
// the site's own BM25 retrieval (kb.js) answers as before. route() turns a match into the chatbot's decision:
|
||||||
|
// - this site's own entry, raw score >= SEM.answer with a clear lead (or the instant-answer pattern agrees): the answer itself
|
||||||
|
// - the instant-answer pattern hit kept when the match agrees (its entry within SEM.agree of the top), or when the match has
|
||||||
|
// no idea (top below SEM.unsure); this site's own entries rank first unless another site is named or clearly closer
|
||||||
|
// - otherwise no instant answer (the regex is overruled by meaning); the entries >= SEM.context feed the AI prompt
|
||||||
|
// suggest() gives the support desk's new-ticket form the closest help answers (KB entries only) the same way, BM25 as the fallback.
|
||||||
|
// Off with NETKB_MATCH=0. Thresholds measured on bge-large-en-v1.5 over the network KB (2026-11-16). Tests: qa/netkb-semantic.test.mjs
|
||||||
|
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||||
|
// Banners, Stack POL). Keep them identical.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const REFRESH_MS = 10 * 60 * 1000;
|
||||||
|
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
|
||||||
|
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
|
||||||
|
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
|
||||||
|
|
||||||
|
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
|
||||||
|
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||||
|
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||||
|
|
||||||
|
async function call(method, route, body, headers, timeoutMs) {
|
||||||
|
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||||
|
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(timeoutMs || 15000),
|
||||||
|
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||||
|
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||||
|
return { status: r.status, body: j };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
|
||||||
|
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
|
||||||
|
async function publish() {
|
||||||
|
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
|
||||||
|
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
|
||||||
|
const body = { name: O.name, url: O.url, entries };
|
||||||
|
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
|
||||||
|
if (h === publishedHash) return { same: true };
|
||||||
|
try {
|
||||||
|
const r = await call('PUT', '/v1/kb', body);
|
||||||
|
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
|
||||||
|
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
|
||||||
|
return r.body;
|
||||||
|
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
|
||||||
|
}
|
||||||
|
// an admin edit: publish a few seconds later (several quick edits go as one)
|
||||||
|
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
|
||||||
|
|
||||||
|
function readCache() {
|
||||||
|
const f = cacheFile(); if (!f) return;
|
||||||
|
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
|
||||||
|
}
|
||||||
|
function writeCache() {
|
||||||
|
const f = cacheFile(); if (!f) return;
|
||||||
|
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
|
||||||
|
}
|
||||||
|
async function refresh() {
|
||||||
|
if (!enabled()) return { skipped: true };
|
||||||
|
try {
|
||||||
|
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
|
||||||
|
stats.lastReadAt = Date.now();
|
||||||
|
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
|
||||||
|
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
|
||||||
|
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
|
||||||
|
writeCache();
|
||||||
|
return { version: merged.version, count: merged.entries.length };
|
||||||
|
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
|
||||||
|
function remote() {
|
||||||
|
const me = siteName(); const out = [];
|
||||||
|
for (const e of merged.entries || []) {
|
||||||
|
if (!e || e.site === me) continue;
|
||||||
|
const s = (merged.sites || {})[e.site] || {};
|
||||||
|
const url = s.url || e.link || '';
|
||||||
|
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
|
||||||
|
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// the network's sites as the hub knows them (name, link), this one left out
|
||||||
|
function sites() {
|
||||||
|
const me = siteName();
|
||||||
|
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- semantic matching (2026-11-16)
|
||||||
|
const SEM = { answer: Number(process.env.NETKB_SEM_ANSWER) || 0.84, margin: 0.02, context: Number(process.env.NETKB_SEM_CONTEXT) || 0.68, unsure: 0.70, band: 0.08, away: 0.06, agree: 0.10, floor: 0.60 };
|
||||||
|
const MATCH_PAUSE_MS = 30000;
|
||||||
|
let matchDownUntil = 0;
|
||||||
|
const mstats = { matches: 0, matchErrors: 0, matchSkipped: 0, matchLastMs: 0, matchLastError: null, semAnswer: 0, semAgree: 0, semRegex: 0, semVeto: 0, semContext: 0 };
|
||||||
|
const matchOn = () => enabled() && process.env.NETKB_MATCH !== '0';
|
||||||
|
// -> the hub's answer {confidence, margin, hits: [{site, id, title, answer, score, boosted, home}]} or null (off, down, slow)
|
||||||
|
async function match(q, o) {
|
||||||
|
o = o || {};
|
||||||
|
if (!matchOn()) return null;
|
||||||
|
if (Date.now() < matchDownUntil) { mstats.matchSkipped++; return null; }
|
||||||
|
const t0 = Date.now();
|
||||||
|
try {
|
||||||
|
const body = { q: String(q || '').slice(0, 600), k: o.k || 6 };
|
||||||
|
if (o.prefer && o.prefer.length) body.prefer = o.prefer;
|
||||||
|
if (o.only && o.only.length) body.only = o.only;
|
||||||
|
const r = await call('POST', '/v1/kb/match', body, undefined, o.timeoutMs || Number(process.env.NETKB_MATCH_MS) || 1500);
|
||||||
|
mstats.matchLastMs = Date.now() - t0;
|
||||||
|
if (r.status !== 200 || !r.body || !Array.isArray(r.body.hits)) throw new Error('match ' + r.status + ' ' + ((r.body && r.body.error) || ''));
|
||||||
|
mstats.matches++;
|
||||||
|
return r.body;
|
||||||
|
} catch (e) { mstats.matchErrors++; mstats.matchLastError = e.message; matchDownUntil = Date.now() + MATCH_PAUSE_MS; return null; }
|
||||||
|
}
|
||||||
|
// msg + { fast: the instant-answer pattern hit (or null), own: this site's entries, prefer: [site ids the question names] }
|
||||||
|
// -> null (no match: the caller keeps its old path) or { via, hit: own entry to answer with | null, hits: [{entry, score}] for the prompt }
|
||||||
|
async function route(msg, o) {
|
||||||
|
o = o || {};
|
||||||
|
// a question that names another site but asks about "here" is about this site (e.g. "I am on InstantAdPay, does my team carry over here?")
|
||||||
|
const prefer = (o.prefer || []).length && !/\b(here|this site|this one)\b/i.test(msg) ? o.prefer : [];
|
||||||
|
const m = await match(msg, { k: 8, prefer });
|
||||||
|
if (!m) return null;
|
||||||
|
const me = siteName();
|
||||||
|
const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||||
|
const rem = new Map(remote().map(e => [e.id, e]));
|
||||||
|
const all = m.hits.map(h => ({ entry: h.site === me ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id), score: Number(h.score) || 0, home: h.site === me })).filter(h => h.entry);
|
||||||
|
let hits = all;
|
||||||
|
const named = prefer.length > 0, fast = o.fast || null;
|
||||||
|
if (!named) { // home-site first: this site's own entries lead; another site's ride behind them only when clearly closer (a thing only that site has)
|
||||||
|
const mine = hits.filter(h => h.home && h.score >= SEM.context);
|
||||||
|
const homeTop = mine.length ? mine[0].score : 0;
|
||||||
|
hits = mine.concat(hits.filter(h => !h.home && h.score >= homeTop + SEM.away));
|
||||||
|
}
|
||||||
|
const top = hits[0];
|
||||||
|
const ctx = top ? hits.filter(h => h.score >= SEM.context && (h.score >= top.score - SEM.band || !h.home)).map(h => ({ entry: h.entry, score: Math.round(h.score * 1000) / 1000 })) : [];
|
||||||
|
const out = (via, hit) => { mstats['sem' + via[0].toUpperCase() + via.slice(1)]++; return { via, hit, hits: ctx, confidence: top ? top.score : 0 }; };
|
||||||
|
if (top && top.home && !named && top.score >= SEM.answer && (Number(m.margin) >= SEM.margin || (fast && String(fast.id) === String(top.entry.id)))) return out('answer', top.entry);
|
||||||
|
if (fast) {
|
||||||
|
const best = all.length ? all[0].score : 0;
|
||||||
|
if (all.some(h => h.home && String(h.entry.id) === String(fast.id) && h.score >= SEM.floor && h.score >= best - SEM.agree)) return out('agree', fast);
|
||||||
|
if (!top || top.score < SEM.unsure) return out('regex', fast);
|
||||||
|
return out('veto', null);
|
||||||
|
}
|
||||||
|
return out('context', null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// support desk suggestions (2026-11-16): the help answers closest to what a signed-in member is typing into a new ticket.
|
||||||
|
// Knowledge-base entries only (published answers, including the ones written from past tickets), never anyone's ticket text.
|
||||||
|
// text + { own: this site's entries, fallback: async q => [{entry}] (BM25) when the hub is slow or down, max }
|
||||||
|
const SUGGEST_MIN = Number(process.env.NETKB_SUGGEST_MIN) || 0.70;
|
||||||
|
const NOT_SUGGESTED = /(^|[-:])support$|^c-refund$/; // the "contact support" entry is no help on the support form itself
|
||||||
|
function suggestItem(e, home, score) {
|
||||||
|
return { id: String(e.id), title: e.title, answer: String(e.answer || '').slice(0, 900), site: home ? '' : (e.siteName || e.site || ''),
|
||||||
|
link: home ? (e.link || '') : (e.go || e.siteUrl || ''), fromTicket: !!(home && e.source === 'ticket'), score: score == null ? null : Math.round(score * 1000) / 1000 };
|
||||||
|
}
|
||||||
|
async function suggest(text, o) {
|
||||||
|
o = o || {};
|
||||||
|
const q = String(text || '').replace(/\s+/g, ' ').trim().slice(0, 600);
|
||||||
|
if (q.replace(/[^A-Za-z0-9]/g, '').length < 10) return { items: [], via: 'short' };
|
||||||
|
const me = siteName(); const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||||
|
const keep = (e, home) => e && !(home && e.handoff) && !NOT_SUGGESTED.test(String(e.id));
|
||||||
|
let items = [], via = 'none';
|
||||||
|
const m = await match(q, { k: 8, timeoutMs: o.timeoutMs || 2000 });
|
||||||
|
if (m) {
|
||||||
|
via = 'semantic'; const top = m.hits.length ? Number(m.hits[0].score) : 0; const rem = new Map(remote().map(e => [e.id, e]));
|
||||||
|
for (const h of m.hits) {
|
||||||
|
if (h.score < SUGGEST_MIN || h.score < top - 0.08) continue;
|
||||||
|
const home = h.site === me; const e = home ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id);
|
||||||
|
if (keep(e, home)) items.push(suggestItem(e, home, h.score));
|
||||||
|
}
|
||||||
|
} else if (typeof o.fallback === 'function') {
|
||||||
|
via = 'bm25';
|
||||||
|
try { for (const x of (await o.fallback(q)) || []) { const e = x && x.entry; const home = !!e && !e.site; if (keep(e, home)) items.push(suggestItem(e, home, null)); } } catch (e) {}
|
||||||
|
}
|
||||||
|
return { items: items.slice(0, o.max || 3), via };
|
||||||
|
}
|
||||||
|
|
||||||
|
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
|
||||||
|
function init(opts) {
|
||||||
|
O = opts || {}; readCache();
|
||||||
|
if (!enabled()) return;
|
||||||
|
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
|
||||||
|
if (first.unref) first.unref();
|
||||||
|
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||||
|
if (timer.unref) timer.unref();
|
||||||
|
}
|
||||||
|
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt, semantic: matchOn(), sem: SEM }, stats, mstats); }
|
||||||
|
function _set(m) { merged = m; } // tests
|
||||||
|
|
||||||
|
const version = () => merged.version || '';
|
||||||
|
function _matchReset() { matchDownUntil = 0; } // tests
|
||||||
|
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, match, route, suggest, SEM, _set, _matchReset };
|
||||||
@@ -12,6 +12,12 @@ const SITES = [
|
|||||||
{ id: 'dlb', code: 'nwdlb', name: 'Downline Banners', url: 'https://downlinebanners.com/{s2}?ref={s1}' },
|
{ id: 'dlb', code: 'nwdlb', name: 'Downline Banners', url: 'https://downlinebanners.com/{s2}?ref={s1}' },
|
||||||
{ id: 'vbb', code: 'nwvbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com/{s2}?ref={s1}' },
|
{ id: 'vbb', code: 'nwvbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com/{s2}?ref={s1}' },
|
||||||
{ id: 'viraladblitz', code: 'nwvab', name: 'ViralAdBlitz', url: 'https://viraladblitz.com/{s2}?ref={s1}' },
|
{ id: 'viraladblitz', code: 'nwvab', name: 'ViralAdBlitz', url: 'https://viraladblitz.com/{s2}?ref={s1}' },
|
||||||
|
{ id: 'viraladsource', code: 'nwvas', name: 'ViralAdSource', url: 'https://viraladsource.com/{s2}?ref={s1}' },
|
||||||
|
{ id: 'yourprogrambuilder', code: 'nwypb', name: 'YourProgramBuilder', url: 'https://yourprogrambuilder.com/{s2}?ref={s1}' },
|
||||||
|
{ id: 'videoappincome', code: 'nwvai', name: 'Video App Income', url: 'https://videoappincome.com/{s2}?ref={s1}' }, // 2026-11-21: s2 = join for the invite page, empty = the sales page
|
||||||
|
{ id: 'socialtube', code: 'nwst', name: 'Social Tube', url: 'https://socialtube.club/{s2}?ref={s1}' }, // 2026-11-22: the network's video gallery; ?ref= keeps the member's credit on every page there
|
||||||
|
{ id: 'fivex', code: 'nw5x', name: '5xYourTeam', url: 'https://5xyourteam.com/{s2}?ref={s1}' },
|
||||||
|
{ id: 'downlinehydra', code: 'nwdh', name: 'DownlineHydra', url: 'https://downlinehydra.com/{s2}?ref={s1}' },
|
||||||
{ id: 'stackpol', code: 'nwsp', name: 'Stack POL', url: 'https://stackpol.com/{s2}?ref={s1}' },
|
{ id: 'stackpol', code: 'nwsp', name: 'Stack POL', url: 'https://stackpol.com/{s2}?ref={s1}' },
|
||||||
{ id: 'earnerscorner', code: 'nwec', name: 'Earners Corner', url: 'https://earnerscorner.com/{s2}' }
|
{ id: 'earnerscorner', code: 'nwec', name: 'Earners Corner', url: 'https://earnerscorner.com/{s2}' }
|
||||||
];
|
];
|
||||||
|
|||||||
+1
-1
@@ -36,7 +36,7 @@ function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list;
|
|||||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', viraladsource: 'nwvas', yourprogrambuilder: 'nwypb', videoappincome: 'nwvai', fivex: 'nw5x', downlinehydra: 'nwdh', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||||
function selfId(req, l) {
|
function selfId(req, l) {
|
||||||
|
|||||||
+246
-24
@@ -3,7 +3,7 @@
|
|||||||
//
|
//
|
||||||
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||||
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||||
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
// sets the loop guard (nsso.tried, 2 minutes) and sends the browser to P.
|
||||||
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||||
// P mints a token bound to R, the state and the email, and sends the browser
|
// P mints a token bound to R, the state and the email, and sends the browser
|
||||||
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||||
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||||
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||||
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
// stops a second bounce for 2 minutes (30 until 2026-11-15, when it blocked Marty's silent sign-in on LinkSpin), signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||||
// bots and non-page fetches never bounce.
|
// bots and non-page fetches never bounce.
|
||||||
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||||
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||||
@@ -24,6 +24,30 @@
|
|||||||
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||||
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||||
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||||
|
//
|
||||||
|
// THE HUB AS THE PROVIDER (Marty approved 2026-11-15; off unless HUB_SSO=on, with HUB_URL, HUB_SECRET (32+) and HUB_SITE or C.hubSite).
|
||||||
|
// The network hub keeps one network sign-in per browser in its own cookie (7 days, renewed on use). With it on:
|
||||||
|
// /sso/start asks the hub (GET <hub>/sso/check?site=<HUB_SITE>&st&to&m) instead of one other site; the hub answers
|
||||||
|
// /sso/in?h=<token> ("h1." token, HMAC-SHA256 with this site's HUB_SECRET under 'hubsso.v1.', iss 'hub', aud = this site,
|
||||||
|
// 60 s, single use, bound to the state cookie) or /sso/in?none=1&hub=1, and then the old pairwise path is tried once as the
|
||||||
|
// fallback (until every site is switched).
|
||||||
|
// Push: a signed-in member's page load (a real top-level navigation only) with no matching nsso.hp cookie goes once through
|
||||||
|
// <hub>/sso/set?site&t=<this site's token for the member> and straight back, so signing in on any site signs in the hub.
|
||||||
|
// Only when the hub answered /health in the last 2 minutes: a hub that is down never takes a page with it.
|
||||||
|
// Activity (Marty 2026-11-15, DownlineHydra "Wake it", the CRM score): a signed-in member's page load pings POST <hub>/v1/activity
|
||||||
|
// {email|wallet, kind 'visit'} at most once per member per day, fire and forget (HUB_URL + HUB_SECRET; HUB_ACTIVITY=0 turns it off).
|
||||||
|
// signOutEverywhere(session): POST <hub>/v1/sso/signout; the hub ends every hub sign-in of that person and tells hooked sites.
|
||||||
|
//
|
||||||
|
// ONE SITES LIST + THE WAY BACK (Marty 2026-11-17: "I logged in to Instant Ad Pay from Viral Ad Source, and it never had a return
|
||||||
|
// path back"). Before, each provider (IAP, LinkSpin) kept its own hand-written `wallets` list; a site missing from it (5xYourTeam
|
||||||
|
// 11-15, ViralAdSource 11-17) was refused at /sso/check and the member was dropped on the provider's dashboard with no way back.
|
||||||
|
// Sites list: a provider also knows every site in the hub's public GET <hub>/v1/sso-sites (HUB_SSO_SITES there; the same list the
|
||||||
|
// hub signs in for). Read at start, every 5 minutes, and once more (2 s at most) when an unknown site asks. Hand-written entries win.
|
||||||
|
// Return links: any provider page with ?return=<site>&to=/path (a known site only, never an open redirect) remembers the way back
|
||||||
|
// in nsso.ret (1 day) and reloads without the two parameters. Signed in already: straight back. After the email-code sign-in (and
|
||||||
|
// after the username step for a new account) the provider's dashboard goes to /sso/resume, which finishes it: /go/<site>?to=/path.
|
||||||
|
// No wallet yet (a wallet site needs one): with C.walletPath the member goes to the provider's wallet step first (nsso.wait), and
|
||||||
|
// afterWallet(req) gives the wallet-link answer its next hop, /sso/resume. The same holds for a deliberate tap (nsso.back).
|
||||||
'use strict';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
@@ -34,16 +58,53 @@ const enabled = () => SECRET().length >= 32;
|
|||||||
const TTL = 60 * 1000; // token life
|
const TTL = 60 * 1000; // token life
|
||||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||||
const STATE_AGE = 300; // seconds: the state cookie
|
const STATE_AGE = 300; // seconds: the state cookie
|
||||||
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
const GO_STATE_AGE = 3600; // seconds: the state cookie on a deliberate tap (time to sign in, pick a username and link a wallet on the provider first; 20 minutes until 2026-11-17)
|
||||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
const BACK_AGE = 3600; // seconds: the provider remembers an unfinished deliberate check while the member signs in (20 minutes until 2026-11-17)
|
||||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
const RET_AGE = 86400; // seconds: a ?return=<site> link remembers the way back (2026-11-17)
|
||||||
|
const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15)
|
||||||
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15)
|
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15)
|
||||||
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||||
|
const PUSH_AGE = 6 * 86400; // seconds: this browser's member is signed in on the hub (the hub's own sign-in lasts 7 days)
|
||||||
|
const HUB_BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||||
|
const HUB_KEY = () => String(process.env.HUB_SECRET || '').trim();
|
||||||
|
const HUB_NAME = () => String(process.env.HUB_SITE || (C && (C.hubSite || C.self)) || '').trim().toLowerCase();
|
||||||
|
const hubCreds = () => /^https?:\/\/[a-z0-9.:-]+$/i.test(HUB_BASE()) && HUB_KEY().length >= 32 && /^[a-z0-9_-]{1,64}$/.test(HUB_NAME());
|
||||||
|
const hubOn = () => String(process.env.HUB_SSO || '').trim().toLowerCase() === 'on' && hubCreds();
|
||||||
|
let hubSeen = 0, hubChecked = 0, hubAsking = null; // last good /health answer, last time we asked
|
||||||
|
// true when the hub answered /health in the last 2 minutes. Asked at most once a minute; while the answer is unknown (first use, or
|
||||||
|
// the last good answer is old) the caller waits for that one question (2 s at most), so a hub that is down costs one page 2 s a minute.
|
||||||
|
async function hubUp() {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - hubChecked >= 60000 && !hubAsking && typeof fetch === 'function') {
|
||||||
|
hubChecked = now;
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||||
|
hubAsking = fetch(HUB_BASE() + '/health', { signal: ac ? ac.signal : undefined }).then(r => { if (r.ok) hubSeen = Date.now(); }).catch(() => {}).finally(() => { clearTimeout(tm); hubAsking = null; });
|
||||||
|
}
|
||||||
|
if (hubAsking && Date.now() - hubSeen >= 120000) await hubAsking;
|
||||||
|
return Date.now() - hubSeen < 120000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the hub's sign-in sites {site: base} (2026-11-17): providers answer every site the hub knows, not only their hand-written list
|
||||||
|
let hubSites = {}, hubSitesAt = 0, hubSitesAsking = null;
|
||||||
|
const SITE_RE = /^[a-z0-9_-]{1,64}$/, BASE_RE = /^https?:\/\/[a-z0-9.:-]+$/i;
|
||||||
|
function loadHubSites() {
|
||||||
|
if (hubSitesAsking) return hubSitesAsking;
|
||||||
|
if (!BASE_RE.test(HUB_BASE()) || typeof fetch !== 'function' || String(process.env.NSSO_HUB_SITES || '') === '0') return Promise.resolve();
|
||||||
|
hubSitesAt = Date.now();
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, 2000);
|
||||||
|
hubSitesAsking = fetch(HUB_BASE() + '/v1/sso-sites', { signal: ac ? ac.signal : undefined }).then(r => (r.ok ? r.json() : null)).then(j => {
|
||||||
|
if (!j || !j.sites || typeof j.sites !== 'object') return;
|
||||||
|
const out = {}; for (const [k, v] of Object.entries(j.sites)) { const b = String(v || '').replace(/\/+$/, ''); if (SITE_RE.test(k) && BASE_RE.test(b)) out[k] = b; }
|
||||||
|
hubSites = out;
|
||||||
|
}).catch(() => {}).finally(() => { clearTimeout(tm); hubSitesAsking = null; });
|
||||||
|
return hubSitesAsking;
|
||||||
|
}
|
||||||
|
const freshSites = () => { if (C && C.wallet && Date.now() - hubSitesAt > 5 * 60 * 1000) loadHubSites(); };
|
||||||
|
|
||||||
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||||
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
|
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() }, walletPath?: the provider's wallet step }
|
||||||
|
|
||||||
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||||
@@ -88,6 +149,77 @@ function verify(tok, o) {
|
|||||||
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hub tokens ("h1.", the hub's format): mint for the hub (push), verify from the hub (sign-in)
|
||||||
|
const hmacHub = x => crypto.createHmac('sha256', HUB_KEY()).update('hubsso.v1.' + x).digest();
|
||||||
|
function mintHub(o) {
|
||||||
|
const now = o.now || Date.now();
|
||||||
|
const t = { iss: HUB_NAME(), aud: 'hub', to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||||
|
if (o.email) t.email = String(o.email).trim().toLowerCase(); else if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||||
|
const body = b64u(JSON.stringify(t));
|
||||||
|
return 'h1.' + body + '.' + b64u(hmacHub(body));
|
||||||
|
}
|
||||||
|
function verifyHub(tok, o) {
|
||||||
|
if (!hubCreds()) return { error: 'off' };
|
||||||
|
const m = /^h1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||||
|
if (!m) return { error: 'malformed' };
|
||||||
|
const want = hmacHub(m[1]), got = unb64u(m[2]);
|
||||||
|
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||||
|
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||||
|
const now = (o && o.now) || Date.now();
|
||||||
|
if (!p || p.iss !== 'hub' || p.aud !== HUB_NAME()) return { error: 'audience' };
|
||||||
|
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||||
|
const st = String((o && o.st) || '');
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||||
|
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||||
|
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||||
|
return { ok: true, iss: 'hub', email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||||
|
}
|
||||||
|
// a signed /v1 call to the hub (the scheme every site already uses): hex HMAC-SHA256(HUB_SECRET, ts + newline + body)
|
||||||
|
async function hubCall(route, body, ms) {
|
||||||
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||||
|
const ac = typeof AbortController === 'function' ? new AbortController() : null; const tm = setTimeout(() => { if (ac) ac.abort(); }, ms || 5000);
|
||||||
|
try {
|
||||||
|
const r = await fetch(HUB_BASE() + route, { method: 'POST', body: raw, signal: ac ? ac.signal : undefined, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': HUB_NAME(), 'X-Hub-Ts': ts, 'X-Hub-Sig': crypto.createHmac('sha256', HUB_KEY()).update(ts + '\n' + raw).digest('hex') } });
|
||||||
|
let j = null; try { j = await r.json(); } catch (e) {}
|
||||||
|
return { status: r.status, json: j };
|
||||||
|
} finally { clearTimeout(tm); }
|
||||||
|
}
|
||||||
|
const who = s => (s && s.email ? { email: String(s.email).toLowerCase() } : s && s.address && WALLET_RE.test(String(s.address).toLowerCase()) ? { wallet: String(s.address).toLowerCase() } : null);
|
||||||
|
const pushTag = w => b64u(crypto.createHmac('sha256', HUB_KEY()).update('push.' + (w.email || w.wallet)).digest()).slice(0, 22);
|
||||||
|
// once per member per day (memory; a restart may ping once more, the hub counts a visit once per 10 minutes anyway)
|
||||||
|
const pinged = new Map(); let pingDay = '';
|
||||||
|
function activity(w) {
|
||||||
|
if (String(process.env.HUB_ACTIVITY || '') === '0' || !hubCreds() || typeof fetch !== 'function') return;
|
||||||
|
const day = new Date().toISOString().slice(0, 10); if (day !== pingDay) { pinged.clear(); pingDay = day; }
|
||||||
|
const k = w.email || w.wallet; if (pinged.has(k)) return; pinged.set(k, 1);
|
||||||
|
hubCall('/v1/activity', Object.assign({ kind: 'visit' }, w), 5000).then(r => { if (r.status >= 500) pinged.delete(k); }).catch(() => { pinged.delete(k); });
|
||||||
|
}
|
||||||
|
// a signed-in request the site already answers (2026-11-16, Marty: "LinkSpin never reports activity"): /api/me, the dashboard
|
||||||
|
// heartbeat (/api/my/ping) and the admin portal call this, so a Control Room tab kept open for days, a browser that sends no
|
||||||
|
// Sec-Fetch headers and a wallet-only session still count the day's visit. The page-load ping in page() only sees full navigations.
|
||||||
|
// s = {email} and/or {address}. Same once-a-day rule as page(). -> true when a ping was due or already sent today.
|
||||||
|
function seen(s) {
|
||||||
|
try {
|
||||||
|
if (!C || !hubCreds()) return false;
|
||||||
|
const w = who(s && s.email ? s : s && s.address ? { address: s.address } : null); if (!w) return false;
|
||||||
|
activity(w); return true;
|
||||||
|
} catch (e) { return false; }
|
||||||
|
}
|
||||||
|
// a real top-level page load of a page (never an API call, an asset, a fetch, a bot or one of our own hops)
|
||||||
|
function pageLoad(req, p) {
|
||||||
|
if (req.method !== 'GET' || isBot(req)) return false;
|
||||||
|
if (req.headers['sec-fetch-dest'] !== 'document' || (req.headers['sec-fetch-mode'] && req.headers['sec-fetch-mode'] !== 'navigate')) return false;
|
||||||
|
if (/^\/(sso|api|go|assets|art|img|fonts|uploads|admin)(\/|$)/.test(p)) return false;
|
||||||
|
return !/\.[a-z0-9]{1,5}$/i.test(p);
|
||||||
|
}
|
||||||
|
async function signOutEverywhere(s) {
|
||||||
|
const w = who(s); if (!w || !hubCreds()) return { ok: false, reason: !w ? 'signed out' : 'hub off' };
|
||||||
|
try { const r = await hubCall('/v1/sso/signout', w, 8000); return r.status === 200 ? Object.assign({ ok: true }, r.json || {}) : { ok: false, reason: 'hub ' + r.status }; }
|
||||||
|
catch (e) { return { ok: false, reason: 'hub unreachable' }; }
|
||||||
|
}
|
||||||
|
|
||||||
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||||
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||||
@@ -129,7 +261,25 @@ const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/;
|
|||||||
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||||
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||||
|
|
||||||
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
|
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); if (hubOn()) { hubSeen = 0; hubChecked = 0; hubUp().catch(() => {}); } hubSites = {}; hubSitesAt = 0; if (C.wallet) loadHubSites(); }
|
||||||
|
|
||||||
|
// a site this provider answers for: its own list first, then the hub's (never itself, never the peer, which has its own path)
|
||||||
|
function siteBase(x) {
|
||||||
|
if (!C || !C.wallet || !SITE_RE.test(String(x || '')) || x === C.self || x === C.peer) return null;
|
||||||
|
if (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x)) return C.wallets[x];
|
||||||
|
if (Object.prototype.hasOwnProperty.call(hubSites, x)) { const b = hubSites[x]; return () => b; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// an unknown site asking: ask the hub once more (at most every 30 s, 2 s at most) before refusing
|
||||||
|
async function siteBaseFresh(x) { let b = siteBase(x); if (!b && C && C.wallet && SITE_RE.test(String(x || '')) && Date.now() - hubSitesAt > 30000) { await loadHubSites(); b = siteBase(x); } return b; }
|
||||||
|
const siteName = x => NAMES[x] || ({ viraladsource: 'ViralAdSource', webworthit: 'WebWorthIt', stackpol: 'Stack POL' })[x] || x;
|
||||||
|
const retOf = req => { const m = /^([a-z0-9_-]{1,64})\|(\/.*)$/.exec(cookies(req)['nsso.ret'] || ''); return m ? { site: m[1], to: safePath(m[2], '/') } : null; };
|
||||||
|
// signed in here, on the way back to a site: its wallet step first when the site needs a wallet this account does not have yet
|
||||||
|
async function backHop(s, site, to, set) {
|
||||||
|
let w = null; try { w = await C.wallet(s); } catch (e) {}
|
||||||
|
if ((!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) && C.walletPath) { set.push(ck('nsso.wait', '1', BACK_AGE, true)); log('back: wallet step first', s.email, 'for ' + siteName(site)); return C.walletPath; }
|
||||||
|
return '/go/' + site + '?to=' + encodeURIComponent(to);
|
||||||
|
}
|
||||||
|
|
||||||
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||||
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||||
@@ -138,9 +288,24 @@ const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
|||||||
async function handle(req, res, u) {
|
async function handle(req, res, u) {
|
||||||
if (!C || req.method !== 'GET') return false;
|
if (!C || req.method !== 'GET') return false;
|
||||||
const p = u.pathname;
|
const p = u.pathname;
|
||||||
|
if (C.wallet && u.searchParams.has('return') && !/^\/(sso|api|go)(\/|$)/.test(p)) { // a site's "sign in / join on <provider>" link: remember the way back (2026-11-17)
|
||||||
|
const site = String(u.searchParams.get('return') || '').toLowerCase(); const to = safePath(u.searchParams.get('to'), '/');
|
||||||
|
const clean = new URL(u.pathname + u.search, 'http://x.invalid'); clean.searchParams.delete('return'); clean.searchParams.delete('to');
|
||||||
|
const here = safePath(clean.pathname + clean.search, '/');
|
||||||
|
const base = isBot(req) ? null : await siteBaseFresh(site);
|
||||||
|
if (!base) return go(res, here); // unknown site (or a bot): the page itself, nothing remembered
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (s && s.email) { // signed in here already: straight back (wallet step first when the site needs one)
|
||||||
|
const set = []; const hop = await backHop(s, site, to, set);
|
||||||
|
set.push(hop === C.walletPath ? ck('nsso.ret', site + '|' + to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||||
|
return go(res, hop, set);
|
||||||
|
}
|
||||||
|
log('return link remembered', null, 'for ' + siteName(site));
|
||||||
|
return go(res, here, [ck('nsso.ret', site + '|' + to, RET_AGE, true), ck('nsso.wait', '', 0, true)]);
|
||||||
|
}
|
||||||
const peerName = NAMES[C.peer] || C.peer;
|
const peerName = NAMES[C.peer] || C.peer;
|
||||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||||
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
const walletBase = siteBase; freshSites(); // the hand-written list, then the hub's sign-in sites (2026-11-17)
|
||||||
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||||
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||||
const to = safePath(u.searchParams.get('to'), '/');
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
@@ -156,28 +321,43 @@ async function handle(req, res, u) {
|
|||||||
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||||
const via = String(u.searchParams.get('via') || '');
|
const via = String(u.searchParams.get('via') || '');
|
||||||
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||||
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
const viaHub = hubOn() && !u.searchParams.get('nohub') && (await hubUp());
|
||||||
|
if (!(enabled() || viaHub) || isBot(req) || notPage(req)) return go(res, to);
|
||||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||||
const c = cookies(req);
|
const c = cookies(req);
|
||||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off']) && !u.searchParams.get('nohub')) return go(res, to);
|
||||||
const st = crypto.randomBytes(16).toString('hex');
|
const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
if (viaHub) { // the hub answers for the whole network; the pairwise provider is the fallback when it has nobody (nsso.via)
|
||||||
|
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true), ck('nsso.via', via || '-', STATE_AGE, true)];
|
||||||
|
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
|
return go(res, HUB_BASE() + '/sso/check?site=' + encodeURIComponent(HUB_NAME()) + '&st=' + st + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||||
|
}
|
||||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||||
}
|
}
|
||||||
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||||
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||||
const clear = [ck('nsso.back', '', 0, true)];
|
const clear = [ck('nsso.back', '', 0, true), ck('nsso.wait', '', 0, true)];
|
||||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) { // no deliberate tap waiting: a ?return=<site> link may be (2026-11-17)
|
||||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
const ret = retOf(req);
|
||||||
|
if (!ret || !siteBase(ret.site)) return go(res, C.defaultPath, clear.concat(ck('nsso.ret', '', 0, true)));
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
if (!s || !s.email) return go(res, C.signinPath(C.defaultPath)); // not signed in yet: keep it for after the sign-in
|
||||||
|
const set = clear.slice(); const hop = await backHop(s, ret.site, ret.to, set);
|
||||||
|
set.push(hop === C.walletPath ? ck('nsso.ret', ret.site + '|' + ret.to, RET_AGE, true) : ck('nsso.ret', '', 0, true));
|
||||||
|
log('back to ' + siteName(ret.site), s.email); return go(res, hop, set);
|
||||||
|
}
|
||||||
|
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')) + '&m=go', clear); // m=go: still a deliberate tap (the wallet step when one is missing)
|
||||||
}
|
}
|
||||||
if (p === '/sso/check') {
|
if (p === '/sso/check') {
|
||||||
const st = String(u.searchParams.get('st') || '');
|
const st = String(u.searchParams.get('st') || '');
|
||||||
const to = safePath(u.searchParams.get('to'), '/');
|
const to = safePath(u.searchParams.get('to'), '/');
|
||||||
const r = String(u.searchParams.get('r') || '');
|
const r = String(u.searchParams.get('r') || '');
|
||||||
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
const wb = r && r !== C.peer ? await siteBaseFresh(r) : null; // a wallet site asking: the token carries the wallet (the hub's sign-in sites too, 2026-11-17)
|
||||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin)
|
||||||
|
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = siteName(aud);
|
||||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
@@ -190,15 +370,30 @@ async function handle(req, res, u) {
|
|||||||
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||||
}
|
}
|
||||||
let w = null;
|
let w = null;
|
||||||
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) {
|
||||||
|
if (u.searchParams.get('m') === 'go' && C.walletPath && !isBot(req)) { // a deliberate tap: link a wallet here first, then /sso/resume finishes the trip (2026-11-17)
|
||||||
|
log('check: no wallet on the account, wallet step first', s.email, 'for ' + forName);
|
||||||
|
const back = new URLSearchParams({ st, to, m: 'go' }); if (r) back.set('r', r);
|
||||||
|
return go(res, C.walletPath, [ck('nsso.back', back.toString(), BACK_AGE, true), ck('nsso.wait', '1', BACK_AGE, true)]);
|
||||||
|
}
|
||||||
|
log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||||
log('token issued', s.email, 'for ' + forName);
|
log('token issued', s.email, 'for ' + forName);
|
||||||
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||||
}
|
}
|
||||||
if (p === '/sso/in') {
|
if (p === '/sso/in') {
|
||||||
const c = cookies(req);
|
const c = cookies(req);
|
||||||
const set = [ck('nsso.st', '', 0, true)];
|
const set = [ck('nsso.st', '', 0, true)];
|
||||||
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
if (u.searchParams.get('none')) {
|
||||||
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
const nto = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||||
|
if (u.searchParams.get('hub') && enabled()) { // nobody on the hub: ask the old pairwise provider once (until every site is switched)
|
||||||
|
const via = String(c['nsso.via'] || ''); set.push(ck('nsso.via', '', 0, true));
|
||||||
|
log('none on the hub, trying ' + (NAMES[via] || peerName));
|
||||||
|
return go(res, '/sso/start?nohub=1&mode=' + (u.searchParams.get('m') === 'go' ? 'go' : 'check') + (via && via !== '-' ? '&via=' + encodeURIComponent(via) : '') + '&to=' + encodeURIComponent(nto), set);
|
||||||
|
}
|
||||||
|
log('none: not signed in on ' + (u.searchParams.get('hub') ? 'the hub' : peerName)); return go(res, C.signinPath(nto), set);
|
||||||
|
}
|
||||||
|
const fromHub = !!u.searchParams.get('h');
|
||||||
|
const v = fromHub ? verifyHub(u.searchParams.get('h'), { st: c['nsso.st'] }) : verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||||
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||||
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||||
@@ -210,21 +405,48 @@ async function handle(req, res, u) {
|
|||||||
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
||||||
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||||
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||||
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
|
if (fromHub) { const w2 = v.wallet && C.from ? { wallet: v.wallet } : { email: v.email }; set.push(ck('nsso.hp', pushTag(w2), PUSH_AGE, true)); } // the hub already has this sign-in
|
||||||
|
log('signed in from ' + (fromHub ? 'the network hub' : (NAMES[v.iss] || peerName)), v.email);
|
||||||
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||||
}
|
}
|
||||||
if (p === '/api/sso/status') {
|
if (p === '/api/sso/status') {
|
||||||
const c = cookies(req); const set = [];
|
const c = cookies(req); const set = [];
|
||||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
const signedIn = !!(s && (s.email || s.address));
|
const signedIn = !!(s && (s.email || s.address));
|
||||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
const out = { peer: hubOn() ? 'the network' : peerName, check: (enabled() || (hubOn() && (await hubUp()))) && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||||
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||||
return sendJson(res, out, set);
|
return sendJson(res, out, set);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
// every GET a site serves passes here first (2026-11-15): a signed-in member's real page load pings the hub's activity once a day and,
|
||||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
// with the hub on, tells the hub about this sign-in once (nsso.hp). -> true when it answered (the redirect through the hub).
|
||||||
|
async function page(req, res, u) {
|
||||||
|
if (!C || !hubCreds()) return false;
|
||||||
|
const p = u.pathname;
|
||||||
|
if (!pageLoad(req, p)) return false;
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
const w = who(s); if (!w) return false;
|
||||||
|
activity(w);
|
||||||
|
if (hubOn() && cookies(req)['nsso.hp'] !== pushTag(w) && (await hubUp())) {
|
||||||
|
log('hub: telling the hub about this sign-in', w.email || null);
|
||||||
|
return go(res, HUB_BASE() + '/sso/set?site=' + encodeURIComponent(HUB_NAME()) + '&t=' + mintHub(Object.assign({ to: p + u.search }, w)), [ck('nsso.hp', pushTag(w), PUSH_AGE, true)]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
// true when this browser came here from a deliberate network tap (nsso.back) or a ?return=<site> link (nsso.ret) and still has to
|
||||||
|
// finish it after signing in. False while it waits on the wallet step (nsso.wait): the dashboard must not bounce it back and forth.
|
||||||
|
const pendingBack = req => { const c = cookies(req); return !!(c['nsso.back'] || retOf(req)) && !c['nsso.wait']; };
|
||||||
|
// the wallet was just linked: the next hop when a way back is waiting (2026-11-17), else null
|
||||||
|
const afterWallet = req => { const c = cookies(req); return c['nsso.back'] || retOf(req) ? '/sso/resume' : null; };
|
||||||
|
// the name of the site a member is on the way back to, for a line on the provider's dashboard; null when none
|
||||||
|
function backName(req) {
|
||||||
|
const c = cookies(req); const ret = retOf(req);
|
||||||
|
if (ret) return siteName(ret.site);
|
||||||
|
if (!c['nsso.back']) return null;
|
||||||
|
const r = new URLSearchParams(c['nsso.back']).get('r'); return siteName(r || (C && C.peer) || '') || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, handle, page, seen, enabled, pendingBack, afterWallet, backName, siteBase, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES, hubOn, hubCreds, signOutEverywhere, mintHub, verifyHub, _hubSeen: t => { hubSeen = t == null ? Date.now() : t; hubChecked = Date.now(); }, _pinged: pinged, _hubSites: o => { if (o) { hubSites = o; hubSitesAt = Date.now(); } return hubSites; } };
|
||||||
|
|||||||
+1
-1
@@ -153,4 +153,4 @@ async function inbound(key, body) {
|
|||||||
}
|
}
|
||||||
// admin Member content (2026-10-18): every postback of every owner
|
// admin Member content (2026-10-18): every postback of every owner
|
||||||
function adminAll() { return J.db.items.map(p => Object.assign(pubItem(p), { owner: p.owner })); }
|
function adminAll() { return J.db.items.map(p => Object.assign(pubItem(p), { owner: p.owner })); }
|
||||||
module.exports = { init, adminAll, EVENTS, validateUrl, fill, deliver, list, create, update, logFor, logForSource, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => { if (!J.db) J.load(); return J.db; }, save: () => J.save() }, init, adminAll, EVENTS, validateUrl, fill, deliver, list, create, update, logFor, logForSource, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound };
|
||||||
|
|||||||
@@ -4,10 +4,14 @@
|
|||||||
// the dashboard. One redemption per code per account; every redemption is logged; optional
|
// the dashboard. One redemption per code per account; every redemption is logged; optional
|
||||||
// cap (max uses) and expiry; codes can be switched off. Storage: MySQL promo_codes +
|
// cap (max uses) and expiry; codes can be switched off. Storage: MySQL promo_codes +
|
||||||
// promo_redemptions, or DATA_DIR/promos.json.
|
// promo_redemptions, or DATA_DIR/promos.json.
|
||||||
|
// starts (2026-11-17, Network Weekend WEEKEND500): a code can be created dormant and open by itself at an exact time (ms; 0 = open
|
||||||
|
// now). Before it opens it answers 'not open yet'. Test clock: setClock(fn) in tests only.
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const db = require('./db');
|
const db = require('./db');
|
||||||
let DATA_DIR = null;
|
let DATA_DIR = null;
|
||||||
|
let clock = () => Date.now();
|
||||||
|
function setClock(fn) { clock = typeof fn === 'function' ? fn : () => Date.now(); }
|
||||||
const norm = c => String(c || '').trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 24);
|
const norm = c => String(c || '').trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '').slice(0, 24);
|
||||||
|
|
||||||
const J = {
|
const J = {
|
||||||
@@ -27,8 +31,8 @@ const D = {
|
|||||||
async get(code) { const r = await db.q('SELECT * FROM promo_codes WHERE code=?', [code]); return r[0] ? row(r[0]) : null; },
|
async get(code) { const r = await db.q('SELECT * FROM promo_codes WHERE code=?', [code]); return r[0] ? row(r[0]) : null; },
|
||||||
async list() { return (await db.q('SELECT * FROM promo_codes ORDER BY created DESC')).map(row); },
|
async list() { return (await db.q('SELECT * FROM promo_codes ORDER BY created DESC')).map(row); },
|
||||||
async put(c) {
|
async put(c) {
|
||||||
await db.q('INSERT INTO promo_codes (code,credits,partner,note,max_uses,expires,active,created,funder) VALUES (?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE funder=VALUES(funder), credits=VALUES(credits), partner=VALUES(partner), note=VALUES(note), max_uses=VALUES(max_uses), expires=VALUES(expires), active=VALUES(active)',
|
await db.q('INSERT INTO promo_codes (code,credits,partner,note,max_uses,expires,active,created,funder,starts) VALUES (?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE funder=VALUES(funder), credits=VALUES(credits), partner=VALUES(partner), note=VALUES(note), max_uses=VALUES(max_uses), expires=VALUES(expires), active=VALUES(active), starts=VALUES(starts)',
|
||||||
[c.code, c.credits, c.partner || null, c.note || null, c.maxUses || 0, c.expires || 0, c.active ? 1 : 0, c.created || Date.now(), c.funder || null]);
|
[c.code, c.credits, c.partner || null, c.note || null, c.maxUses || 0, c.expires || 0, c.active ? 1 : 0, c.created || Date.now(), c.funder || null, c.starts || 0]);
|
||||||
return this.get(c.code);
|
return this.get(c.code);
|
||||||
},
|
},
|
||||||
async uses(code) { const r = await db.q('SELECT COUNT(*) n FROM promo_redemptions WHERE code=?', [code]); return Number(r[0].n); },
|
async uses(code) { const r = await db.q('SELECT COUNT(*) n FROM promo_redemptions WHERE code=?', [code]); return Number(r[0].n); },
|
||||||
@@ -36,7 +40,7 @@ const D = {
|
|||||||
async addRedemption(r) { await db.q('INSERT IGNORE INTO promo_redemptions (code,email,credits,via,ts) VALUES (?,?,?,?,?)', [r.code, r.email, r.credits, r.via, r.ts]); },
|
async addRedemption(r) { await db.q('INSERT IGNORE INTO promo_redemptions (code,email,credits,via,ts) VALUES (?,?,?,?,?)', [r.code, r.email, r.credits, r.via, r.ts]); },
|
||||||
async redemptions(code, n) { const rows = code ? await db.q('SELECT * FROM promo_redemptions WHERE code=? ORDER BY ts DESC LIMIT ?', [code, Number(n) || 200]) : await db.q('SELECT * FROM promo_redemptions ORDER BY ts DESC LIMIT ?', [Number(n) || 200]); return rows.map(r => ({ code: r.code, email: r.email, credits: Number(r.credits), via: r.via, ts: Number(r.ts) })); }
|
async redemptions(code, n) { const rows = code ? await db.q('SELECT * FROM promo_redemptions WHERE code=? ORDER BY ts DESC LIMIT ?', [code, Number(n) || 200]) : await db.q('SELECT * FROM promo_redemptions ORDER BY ts DESC LIMIT ?', [Number(n) || 200]); return rows.map(r => ({ code: r.code, email: r.email, credits: Number(r.credits), via: r.via, ts: Number(r.ts) })); }
|
||||||
};
|
};
|
||||||
const row = r => ({ code: r.code, funder: r.funder || null, credits: Number(r.credits), partner: r.partner || '', note: r.note || '', maxUses: Number(r.max_uses) || 0, expires: Number(r.expires) || 0, active: !!Number(r.active), created: Number(r.created) });
|
const row = r => ({ code: r.code, funder: r.funder || null, credits: Number(r.credits), partner: r.partner || '', note: r.note || '', maxUses: Number(r.max_uses) || 0, expires: Number(r.expires) || 0, starts: Number(r.starts) || 0, active: !!Number(r.active), created: Number(r.created) });
|
||||||
const impl = () => db.enabled() ? D : J;
|
const impl = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
|
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
|
||||||
@@ -44,7 +48,7 @@ async function create(c) {
|
|||||||
const code = norm(c.code); if (!code || code.length < 3) return { error: 'Code must be 3 to 24 letters or numbers.' };
|
const code = norm(c.code); if (!code || code.length < 3) return { error: 'Code must be 3 to 24 letters or numbers.' };
|
||||||
const credits = Math.floor(Number(c.credits)); if (!(credits > 0) || credits > 100000) return { error: 'Credits must be between 1 and 100,000.' };
|
const credits = Math.floor(Number(c.credits)); if (!(credits > 0) || credits > 100000) return { error: 'Credits must be between 1 and 100,000.' };
|
||||||
const cur = await impl().get(code);
|
const cur = await impl().get(code);
|
||||||
const saved = await impl().put({ code, credits, funder: c.funder ? String(c.funder).toLowerCase() : (cur && cur.funder) || null, partner: String(c.partner || '').slice(0, 80), note: String(c.note || '').slice(0, 200), maxUses: Math.max(0, Math.floor(Number(c.maxUses) || 0)), expires: c.expires ? Number(new Date(c.expires)) || 0 : 0, active: c.active !== false && c.active !== 0 && c.active !== '0', created: cur ? cur.created : Date.now() });
|
const saved = await impl().put({ code, credits, funder: c.funder ? String(c.funder).toLowerCase() : (cur && cur.funder) || null, partner: String(c.partner || '').slice(0, 80), note: String(c.note || '').slice(0, 200), maxUses: Math.max(0, Math.floor(Number(c.maxUses) || 0)), expires: c.expires ? Number(new Date(c.expires)) || 0 : 0, starts: c.starts !== undefined ? (c.starts ? Number(new Date(c.starts)) || 0 : 0) : (cur && cur.starts) || 0, active: c.active !== false && c.active !== 0 && c.active !== '0', created: cur ? cur.created : Date.now() });
|
||||||
return { ok: true, code: saved };
|
return { ok: true, code: saved };
|
||||||
}
|
}
|
||||||
async function setActive(code, active) { const c = await impl().get(norm(code)); if (!c) return { error: 'No such code.' }; await impl().put(Object.assign(c, { active: !!active })); return { ok: true }; }
|
async function setActive(code, active) { const c = await impl().get(norm(code)); if (!c) return { error: 'No such code.' }; await impl().put(Object.assign(c, { active: !!active })); return { ok: true }; }
|
||||||
@@ -52,7 +56,8 @@ async function setActive(code, active) { const c = await impl().get(norm(code));
|
|||||||
async function check(code, email) {
|
async function check(code, email) {
|
||||||
const k = norm(code); if (!k) return { error: 'Enter a promo code.' };
|
const k = norm(code); if (!k) return { error: 'Enter a promo code.' };
|
||||||
const c = await impl().get(k); if (!c || !c.active) return { error: 'That promo code is not valid.' };
|
const c = await impl().get(k); if (!c || !c.active) return { error: 'That promo code is not valid.' };
|
||||||
if (c.expires && Date.now() > c.expires) return { error: 'That promo code has expired.' };
|
if (c.starts && clock() < c.starts) return { error: 'That promo code is not open yet.' };
|
||||||
|
if (c.expires && clock() > c.expires) return { error: 'That promo code has expired.' };
|
||||||
if (email && await impl().redeemed(k, email)) return { error: 'You already used that promo code.' };
|
if (email && await impl().redeemed(k, email)) return { error: 'You already used that promo code.' };
|
||||||
if (c.maxUses && (await impl().uses(k)) >= c.maxUses) return { error: 'That promo code has been fully redeemed.' };
|
if (c.maxUses && (await impl().uses(k)) >= c.maxUses) return { error: 'That promo code has been fully redeemed.' };
|
||||||
return null;
|
return null;
|
||||||
@@ -71,4 +76,4 @@ async function adminView() {
|
|||||||
return { codes, recent: await impl().redemptions(null, 100) };
|
return { codes, recent: await impl().redemptions(null, 100) };
|
||||||
}
|
}
|
||||||
async function byFunder(email) { return (await impl().list()).filter(c => c.funder === String(email || '').toLowerCase()); }
|
async function byFunder(email) { return (await impl().list()).filter(c => c.funder === String(email || '').toLowerCase()); }
|
||||||
module.exports = { init, create, setActive, check, redeem, adminView, norm, byFunder };
|
module.exports = { setClock, init, create, setActive, check, redeem, adminView, norm, byFunder };
|
||||||
|
|||||||
+3
-3
@@ -8,7 +8,7 @@
|
|||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/cr.css?v=20261114tu">
|
<link rel="stylesheet" href="/assets/cr.css?v=20261114tu">
|
||||||
<style>@import url("/assets/site.css?v=ls20261101t") layer(legacy);</style>
|
<style>@import url("/assets/site.css?v=ls20261118rd") layer(legacy);</style>
|
||||||
<link rel="stylesheet" href="/assets/tools.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/tools.css?v=20261101t">
|
||||||
<link rel="stylesheet" href="/assets/admin.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/admin.css?v=20261101t">
|
||||||
</head>
|
</head>
|
||||||
@@ -548,8 +548,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||||
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script><script src="/assets/admin-launchweek.js?v=20261105lw"></script>
|
<script src="/assets/tankready.js?v=20261118rd"></script><script src="/assets/admin.js?v=20261118rd"></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>
|
||||||
|
|||||||
+3
-2
@@ -60,6 +60,7 @@
|
|||||||
<label class="lbl">Headline (60)<input class="field" id="fTitle" maxlength="60"></label>
|
<label class="lbl">Headline (60)<input class="field" id="fTitle" maxlength="60"></label>
|
||||||
<label class="lbl">One line (140)<input class="field" id="fBody" maxlength="140"></label>
|
<label class="lbl">One line (140)<input class="field" id="fBody" maxlength="140"></label>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="aiRow" hidden style="margin-top:10px"><button class="btn sm" type="button" id="aiWrite">Write my ad from my link</button> <span class="muted" style="font-size:12px">Put your link in Where the click goes first. We read that page and suggest 3 text ads using only what it says. Nothing launches until you tap Launch.</span><div id="aiList" hidden style="margin-top:8px"></div></div>
|
||||||
<div id="prev" style="margin-top:12px"></div>
|
<div id="prev" style="margin-top:12px"></div>
|
||||||
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px;align-items:center"><button class="btn pri" type="button" id="fGo">Launch</button><button class="btn ghost" type="button" id="fCancel">Cancel</button><span class="led" id="fCost"></span></div>
|
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px;align-items:center"><button class="btn pri" type="button" id="fGo">Launch</button><button class="btn ghost" type="button" id="fCancel">Cancel</button><span class="led" id="fCost"></span></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -75,8 +76,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/ads-screen.js?v=20261114tu"></script>
|
<script src="/assets/ads-screen.js?v=20261117aiw"></script>
|
||||||
<script src="/assets/fuel.js?v=20261113sso"></script>
|
<script src="/assets/fuel.js?v=20261113sso"></script>
|
||||||
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -301,7 +301,13 @@
|
|||||||
// 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.opensAt > Date.now() ? ' <span class="badge amber" title="New sign-up: hand adoption opens 24 hours after they joined">Opens ' + when(w.opensAt) + '</span>' : '') + (w.ready ? ' <span class="badge" style="background:var(--ok-soft);border-color:var(--ok);color:var(--ok)">Ready to activate · ' + left(w) + '</span>' : '');
|
const rb = w => (w.opensAt > Date.now() ? ' <span class="badge amber" title="New sign-up: hand adoption opens 24 hours after they joined">Opens ' + when(w.opensAt) + '</span>' : '') + (w.ready ? ' <span class="badge" style="background:var(--ok-soft);border-color:var(--ok);color:var(--ok)">Ready to activate · ' + left(w) + '</span>' : '');
|
||||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
|
// readiness (2026-11-18, network hub): hottest first, stage + heat + last action + how they got here; the hub down = the old table
|
||||||
|
const RD = window.TankReady; const rdOn = RD && r.waiting.some(w => w.rd);
|
||||||
|
const wl = rdOn ? r.waiting.slice().sort((a, b) => RD.score(b) - RD.score(a)) : r.waiting;
|
||||||
|
const rs = r.readiness || {}; const rc = rs.counts || {}; const cnt = o => Object.entries(o || {}).sort((a, b) => b[1] - a[1]).map(([k, v]) => k + ' ' + v).join(', ');
|
||||||
|
$('tankAdmSub').textContent += rs.on ? (rs.ok === false ? ' · readiness: hub not answering (' + (rs.error || '') + ')' : rc.n ? ' · readiness: how they got here ' + cnt(rc.reasons) + ' · stages ' + cnt(rc.stages) + ' · heat ' + cnt(rc.bands) : ' · readiness: loading') : ' · readiness off';
|
||||||
|
const cols = rdOn ? 5 : 4;
|
||||||
|
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th>' + (rdOn ? '<th>Readiness (hottest first)</th>' : '') + '</tr>' + (wl.length ? wl.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td>' + (rdOn ? '<td>' + (w.rd ? RD.html(w.rd) : '<span class="muted small">no answer</span>') + '</td>' : '') + '</tr>').join('') : '<tr><td colspan="' + cols + '" class="muted">empty</td></tr>')
|
||||||
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (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' || a.status === 'invited' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' || a.status === 'invited' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
@@ -1093,7 +1099,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, 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)' };
|
const SITE_META = { loginAdEveryHours: 'Login ad: show again on the next member page once the last finished view is this many hours old (default 3)', noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', 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>'
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// viewer, member zones and the partner network, and earn credits by viewing. Types are limited to the three Marty chose.
|
// viewer, member zones and the partner network, and earn credits by viewing. Types are limited to the three Marty chose.
|
||||||
(function () {
|
(function () {
|
||||||
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
|
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
|
||||||
let D = null, EARN = null, TYPE = 'banner', SPINS = [], HOSTS = [], IMG = '';
|
let D = null, EARN = null, TYPE = 'banner', SPINS = [], HOSTS = [], IMG = '', AIW = false;
|
||||||
CR.mount({ active: 'ads', title: 'Ads', sub: 'loading', actions: '<button class="btn pri" type="button" id="newBtn">+ New ad</button>' });
|
CR.mount({ active: 'ads', title: 'Ads', sub: 'loading', actions: '<button class="btn pri" type="button" id="newBtn">+ New ad</button>' });
|
||||||
const NOTE = {
|
const NOTE = {
|
||||||
banner: 'Runs in the ad viewer, in every member zone on outside sites, and on the partner network. Views are timed on the server. Spends purchased or earned credits.',
|
banner: 'Runs in the ad viewer, in every member zone on outside sites, and on the partner network. Views are timed on the server. Spends purchased or earned credits.',
|
||||||
@@ -148,7 +148,7 @@
|
|||||||
window.addEventListener('storage', e => { if (e.key === 'iap-view-done') earnRefresh(); });
|
window.addEventListener('storage', e => { if (e.key === 'iap-view-done') earnRefresh(); });
|
||||||
$('earnClaim').addEventListener('click', async () => { try { const r = await api('/api/my/claim', {}); toast('+' + r.credited + ' credits' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Spend them on an ad.'); load(); } catch (e) { toast(e.message, true); } });
|
$('earnClaim').addEventListener('click', async () => { try { const r = await api('/api/my/claim', {}); toast('+' + r.credited + ' credits' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Spend them on an ad.'); load(); } catch (e) { toast(e.message, true); } });
|
||||||
// -- composer
|
// -- composer
|
||||||
function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login';
|
function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('aiRow').hidden = t !== 'text' || !AIW; $('fCap').parentElement.hidden = t === 'login';
|
||||||
const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget');
|
const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget');
|
||||||
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' : '';
|
||||||
@@ -185,6 +185,23 @@
|
|||||||
setType(TYPE);
|
setType(TYPE);
|
||||||
});
|
});
|
||||||
$('fCancel').addEventListener('click', () => { $('composer').hidden = true; });
|
$('fCancel').addEventListener('click', () => { $('composer').hidden = true; });
|
||||||
|
// the AI ad writer (Marty 2026-11-17): 3 text ads the network hub writes only from the member's own page; picking one fills the
|
||||||
|
// headline and line to edit. Shown only when the hub answers it is on.
|
||||||
|
CR.get('/api/my/adwriter').then(w => { AIW = !!(w && w.on); if (!$('composer').hidden) setType(TYPE); }).catch(() => { AIW = false; });
|
||||||
|
{ let opts = [];
|
||||||
|
$('aiWrite').addEventListener('click', async () => {
|
||||||
|
const box = $('aiList'), url = $('fTarget').value.trim(); box.hidden = false;
|
||||||
|
if (!/^https?:\/\/\S+\.\S+/i.test(url)) { box.innerHTML = '<span class="muted">Put your link in Where the click goes first (starting with https://), or pick a spin link, then tap the button again.</span>'; $('fTarget').focus(); return; }
|
||||||
|
$('aiWrite').disabled = true; box.innerHTML = '<span class="muted">Reading your page and writing 3 ads. This takes a few seconds...</span>';
|
||||||
|
let r; try { r = await api('/api/my/adwriter', { url, kind: 'text' }); } catch (e) { r = { error: e.message || 'The ad writer did not answer. Try again in a minute.' }; }
|
||||||
|
$('aiWrite').disabled = false;
|
||||||
|
if (r.error) { box.innerHTML = '<span class="bad">' + esc(r.error) + '</span>'; return; }
|
||||||
|
opts = r.options || [];
|
||||||
|
box.innerHTML = '<div class="muted" style="font-size:12px;margin-bottom:6px">Tap one to use it. Check every word is true for your offer before you launch.' + (typeof r.left === 'number' ? ' Ad writes left today: ' + r.left + '.' : '') + '</div>'
|
||||||
|
+ opts.map((o, i) => '<button type="button" class="btn ghost" data-ai="' + i + '" style="display:block;width:100%;text-align:left;margin:0 0 6px;white-space:normal;height:auto"><b>' + esc(o.headline) + '</b><br><span class="ink2">' + esc(o.line || '') + '</span></button>').join('');
|
||||||
|
box.querySelectorAll('button[data-ai]').forEach(b => b.addEventListener('click', () => { const o = opts[Number(b.dataset.ai)]; $('fTitle').value = o.headline; $('fBody').value = o.line || ''; box.hidden = true; preview(); toast('Filled in. Edit it as you like, then tap Launch.'); }));
|
||||||
|
});
|
||||||
|
}
|
||||||
$('fGo').addEventListener('click', async () => {
|
$('fGo').addEventListener('click', async () => {
|
||||||
const body = { type: TYPE, name: $('fName').value, targetUrl: $('fTarget').value.trim(), budget: Number($('fBudget').value), geo: $('fGeo').value };
|
const body = { type: TYPE, name: $('fName').value, targetUrl: $('fTarget').value.trim(), budget: Number($('fBudget').value), geo: $('fGeo').value };
|
||||||
if (TYPE !== 'login' && $('fCap').value) body.dailyCap = Number($('fCap').value);
|
if (TYPE !== 'login' && $('fCap').value) body.dailyCap = Number($('fCap').value);
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ window.IAP = (function () {
|
|||||||
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
||||||
+ '<a href="/">How it works</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a><a href="/support">Support</a>'
|
+ '<a href="/">How it works</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a><a href="/support">Support</a>'
|
||||||
+ '<a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
+ '<a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||||
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
|
+ '<div style="margin-top:10px">© 2026 TrustClickz</div>';
|
||||||
document.body.appendChild(f);
|
document.body.appendChild(f);
|
||||||
renderNetworkLine(f);
|
renderNetworkLine(f);
|
||||||
}
|
}
|
||||||
@@ -313,3 +313,6 @@ window.IAP = (function () {
|
|||||||
a.href = '/go/iap?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
a.href = '/go/iap?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
||||||
}, true);
|
}, true);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// Network Weekend ribbon (Marty 2026-11-17): netweekend.js paints it only while a network event is live (dates from the hub)
|
||||||
|
(function () { try { if (window.__nwRibbon || document.querySelector('script[src^="/assets/netweekend.js"]')) return; var s = document.createElement('script'); s.src = '/assets/netweekend.js?v=20261117a'; s.defer = true; s.setAttribute('data-site', 'linkspin'); (document.head || document.documentElement).appendChild(s); } catch (e) {} })();
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ window.CR = (function () {
|
|||||||
window.addEventListener('hashchange', () => { paintRail(); focusAnchor(); });
|
window.addEventListener('hashchange', () => { paintRail(); focusAnchor(); });
|
||||||
focusAnchor();
|
focusAnchor();
|
||||||
$('crRailTog').addEventListener('click', () => { const wide = !app.classList.contains('wide'); app.classList.toggle('wide', wide); try { localStorage.setItem('cr.rail', wide ? 'wide' : 'narrow'); } catch (e) {} });
|
$('crRailTog').addEventListener('click', () => { const wide = !app.classList.contains('wide'); app.classList.toggle('wide', wide); try { localStorage.setItem('cr.rail', wide ? 'wide' : 'narrow'); } catch (e) {} });
|
||||||
$('crUserBtn').addEventListener('click', async e => { e.preventDefault(); if (!ME || !ME.signedIn) return signInFlow(() => location.reload()); const v = await dialog({ title: ME.username ? '@' + ME.username : (ME.email || 'Account'), text: 'Signed in on LinkSpin. Your classic dashboard is still at /my.', ok: 'Sign out', no: 'Close', danger: true }); if (v) { try { await api('/api/auth/logout'); } catch (er) {} location.reload(); } });
|
$('crUserBtn').addEventListener('click', async e => { e.preventDefault(); if (!ME || !ME.signedIn) return signInFlow(() => location.reload()); const v = await dialog({ title: ME.username ? '@' + ME.username : (ME.email || 'Account'), text: 'Signed in on LinkSpin. Your classic dashboard is still at /my.', ok: 'Sign out', no: 'Close', danger: true }); if (v) { const all = await dialog({ title: 'Sign out where?', text: 'Only LinkSpin, or every network site (InstantAdPay, LinkSpin and the others) at once?', ok: 'Everywhere', no: 'Only LinkSpin' }); try { await api(all ? '/api/auth/logout-everywhere' : '/api/auth/logout'); } catch (er) {} location.reload(); } });
|
||||||
clock(); setInterval(clock, 30000);
|
clock(); setInterval(clock, 30000);
|
||||||
paintTheme();
|
paintTheme();
|
||||||
}
|
}
|
||||||
@@ -195,9 +195,11 @@ window.CR = (function () {
|
|||||||
go.addEventListener('click', step);
|
go.addEventListener('click', step);
|
||||||
host.querySelector('.modal').addEventListener('keydown', e => { if (e.key === 'Enter') step(); });
|
host.querySelector('.modal').addEventListener('keydown', e => { if (e.key === 'Enter') step(); });
|
||||||
}
|
}
|
||||||
|
// login ad on the member's clock (Marty 2026-11-15): every Control Room page asks; the server answers with an ad only when the
|
||||||
|
// last finished view is older than loginAdEveryHours (loginadclock.js), and the end of the countdown restarts that clock
|
||||||
|
let laAsked = false;
|
||||||
async function loginAd() {
|
async function loginAd() {
|
||||||
let seen = false; try { seen = !!sessionStorage.getItem('ls.la'); } catch (e) {}
|
if (laAsked) return; laAsked = true;
|
||||||
if (seen) return; try { sessionStorage.setItem('ls.la', '1'); } catch (e) {}
|
|
||||||
let ad = null; try { ad = (await get('/api/ads/slot?type=login')).ad; } catch (e) { return; }
|
let ad = null; try { ad = (await get('/api/ads/slot?type=login')).ad; } catch (e) { return; }
|
||||||
if (!ad || !ad.targetUrl) return;
|
if (!ad || !ad.targetUrl) return;
|
||||||
await new Promise(done => {
|
await new Promise(done => {
|
||||||
@@ -210,7 +212,7 @@ window.CR = (function () {
|
|||||||
back.querySelector('#laOpen').addEventListener('click', () => {
|
back.querySelector('#laOpen').addEventListener('click', () => {
|
||||||
window.open(ad.targetUrl, '_blank'); back.querySelector('#laOpen').disabled = true;
|
window.open(ad.targetUrl, '_blank'); back.querySelector('#laOpen').disabled = true;
|
||||||
let left = ad.dwell || 10; const t = back.querySelector('#laTimer'); t.hidden = false; t.textContent = left + ' s';
|
let left = ad.dwell || 10; const t = back.querySelector('#laTimer'); t.hidden = false; t.textContent = left + ' s';
|
||||||
const iv = setInterval(() => { left -= 1; if (left > 0) { t.textContent = left + ' s'; return; } clearInterval(iv); t.textContent = 'done'; back.querySelector('#laStatus').textContent = 'Thanks for the look.'; back.querySelector('#laGo').hidden = false; }, 1000);
|
const iv = setInterval(() => { left -= 1; if (left > 0) { t.textContent = left + ' s'; return; } clearInterval(iv); t.textContent = 'done'; fetch('/api/ads/login/seen', { method: 'POST' }).catch(() => {}); back.querySelector('#laStatus').textContent = 'Thanks for the look.'; back.querySelector('#laGo').hidden = false; }, 1000);
|
||||||
});
|
});
|
||||||
back.querySelector('#laGo').addEventListener('click', () => { back.remove(); done(); });
|
back.querySelector('#laGo').addEventListener('click', () => { back.remove(); done(); });
|
||||||
});
|
});
|
||||||
@@ -283,7 +285,10 @@ window.CR = (function () {
|
|||||||
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(); }); };
|
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();
|
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); }); }
|
// a network sign-in hop waiting on this sign-in (another site asked "Sign in with LinkSpin" while signed out here): finish it
|
||||||
|
// after the login ad, back to the site and page it came from, never left on the Control Room (2026-11-15)
|
||||||
|
const hopBack = m => { if (m && m.signedIn && m.nssoBack && m.username) { location.href = '/sso/resume'; return true; } return false; };
|
||||||
|
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(); if (hopBack(m)) return; inviteCard(m); return onReady(m); } signInFlow(async r => { whoPaint(r); themeSync(r); strip(); helpBadge(); let m2 = await me(true); m2 = await ensureUsername(m2); await loginAd(); if (hopBack(m2)) return; inviteCard(m2); onReady(m2 && m2.signedIn ? m2 : 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 '';
|
||||||
|
|||||||
@@ -37,7 +37,9 @@
|
|||||||
+ '<label>What is it about?<select class="field" id="hnCat">' + CATS.map(c => '<option>' + esc(c) + '</option>').join('') + '</select></label>'
|
+ '<label>What is it about?<select class="field" id="hnCat">' + CATS.map(c => '<option>' + esc(c) + '</option>').join('') + '</select></label>'
|
||||||
+ '<label>Subject<input class="field" id="hnSubject" maxlength="140" placeholder="A few words, like: my spin link stopped rotating"></label>'
|
+ '<label>Subject<input class="field" id="hnSubject" maxlength="140" placeholder="A few words, like: my spin link stopped rotating"></label>'
|
||||||
+ '<label>Message<textarea class="field" id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea></label>'
|
+ '<label>Message<textarea class="field" id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea></label>'
|
||||||
|
+ '<div id="hnSuggest" class="hsg" hidden aria-live="polite"></div>'
|
||||||
+ '<div class="acts"><button class="btn pri" type="button" id="hnSend">Send to support</button><button class="btn" type="button" id="hnCancel">Cancel</button><span class="hmsg" id="hnMsg"></span></div></div>';
|
+ '<div class="acts"><button class="btn pri" type="button" id="hnSend">Send to support</button><button class="btn" type="button" id="hnCancel">Cancel</button><span class="hmsg" id="hnMsg"></span></div></div>';
|
||||||
|
suggest();
|
||||||
$('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
$('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
||||||
const send = $('hnSend');
|
const send = $('hnSend');
|
||||||
send.addEventListener('click', async () => {
|
send.addEventListener('click', async () => {
|
||||||
@@ -50,6 +52,27 @@
|
|||||||
});
|
});
|
||||||
$('hnSubject').focus();
|
$('hnSubject').focus();
|
||||||
}
|
}
|
||||||
|
// help answers while typing (2026-11-16): debounced, from the KB only (the hub's semantic match); a suggestion never blocks Send
|
||||||
|
function suggest() {
|
||||||
|
const box = $('hnSuggest'), subj = $('hnSubject'), body = $('hnBody');
|
||||||
|
if (!box || !subj || !body) return;
|
||||||
|
let timer = null, seq = 0, last = '';
|
||||||
|
const run = async () => {
|
||||||
|
const text = (subj.value + ' ' + body.value).replace(/\s+/g, ' ').trim();
|
||||||
|
if (text.replace(/[^A-Za-z0-9]/g, '').length < 10) { box.hidden = true; box.innerHTML = ''; last = ''; return; }
|
||||||
|
if (text === last) return; last = text; const mine = ++seq;
|
||||||
|
let r; try { r = await CR.api('/api/my/support/suggest', { subject: subj.value, body: body.value }); } catch (e) { return; }
|
||||||
|
if (mine !== seq || !document.body.contains(box)) return;
|
||||||
|
const items = (r && r.items) || [];
|
||||||
|
if (!items.length) { box.hidden = true; box.innerHTML = ''; return; }
|
||||||
|
box.innerHTML = '<p class="hsg-h"><b>These answers may help</b> <span>You can still send your ticket.</span></p>'
|
||||||
|
+ items.map(i => '<details><summary>' + esc(i.title) + (i.site ? ' <span class="hsg-s">(' + esc(i.site) + ')</span>' : '') + (i.fromTicket ? ' <span class="hsg-s">from a past ticket</span>' : '') + '</summary>'
|
||||||
|
+ '<div class="hsg-b">' + linkify(i.answer) + (i.link && i.site ? '<br><a href="' + esc(i.link) + '" target="_blank" rel="noopener">Open ' + esc(i.site) + '</a>' : '') + '</div></details>').join('');
|
||||||
|
box.hidden = false;
|
||||||
|
};
|
||||||
|
const kick = () => { clearTimeout(timer); timer = setTimeout(run, 700); };
|
||||||
|
subj.addEventListener('input', kick); body.addEventListener('input', kick);
|
||||||
|
}
|
||||||
async function open(ref) {
|
async function open(ref) {
|
||||||
host().innerHTML = '<div class="panel"><span class="muted">loading</span></div>';
|
host().innerHTML = '<div class="panel"><span class="muted">loading</span></div>';
|
||||||
let v; try { v = await CR.get('/api/my/support/' + encodeURIComponent(ref)); }
|
let v; try { v = await CR.get('/api/my/support/' + encodeURIComponent(ref)); }
|
||||||
|
|||||||
+14
-3
@@ -1274,6 +1274,7 @@
|
|||||||
}
|
}
|
||||||
// ── holding tank: waiting members, adopt, my open adoptions ──
|
// ── holding tank: waiting members, adopt, my open adoptions ──
|
||||||
const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; };
|
const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; };
|
||||||
|
let TANK_WARM_ONLY = false; // the "Warm or hot only" toggle on the holding tank (2026-11-18)
|
||||||
async function loadTank() {
|
async function loadTank() {
|
||||||
const el = $('tankList'); if (!el) return;
|
const el = $('tankList'); if (!el) return;
|
||||||
try {
|
try {
|
||||||
@@ -1293,10 +1294,17 @@
|
|||||||
const opens = w => w.opensAt > Date.now(); // new sign-up: they have 24 hours to say who invited them
|
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 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) => (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>'
|
// readiness (2026-11-18, network hub): hottest first inside the usual groups, a "Warm or hot" toggle, and under each lead its stage,
|
||||||
+ '<span class="em">joined ' + ago(w.joined) + '</span>'
|
// heat, last action and how they got here; the hub down = the list exactly as before
|
||||||
|
const RD = window.TankReady; const rdOn = !!(RD && r.waiting.some(w => w.rd));
|
||||||
|
const heatOrder = (a, b) => (rdOn ? RD.score(b) - RD.score(a) : 0);
|
||||||
|
const list = r.waiting.filter(w => !(rdOn && TANK_WARM_ONLY) || (w.rd && w.rd.heat && w.rd.heat.score >= 40));
|
||||||
|
const bar = rdOn ? '<div class="rd-bar"><span class="small muted">Hottest first</span> <button type="button" class="btn sec small' + (TANK_WARM_ONLY ? ' on' : '') + '" id="tankWarmOnly" aria-pressed="' + (TANK_WARM_ONLY ? 'true' : 'false') + '">' + (TANK_WARM_ONLY ? 'Showing warm or hot only' : 'Warm or hot only') + '</button> <span class="small muted">' + list.length + ' of ' + r.waiting.length + '</span></div>' : '';
|
||||||
|
el.innerHTML = bar + (list.length ? list.slice().sort((a, b) => (opens(a) ? 1 : 0) - (opens(b) ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || heatOrder(a, b)).map(w => '<div class="lin-row' + (w.rd ? ' rd-row' : '') + '"><span class="nm">' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '</span>'
|
||||||
|
+ '<span class="em">joined ' + ago(w.joined) + (w.rd && RD ? RD.html(w.rd) : '') + '</span>'
|
||||||
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
|
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
|
||||||
+ (r.eligible && !opens(w) ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('');
|
+ (r.eligible && !opens(w) ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('') : '<p class="muted small">Nobody warm or hot is waiting right now. Switch the filter off to see everyone.</p>');
|
||||||
|
{ const t = $('tankWarmOnly'); if (t) t.addEventListener('click', () => { TANK_WARM_ONLY = !TANK_WARM_ONLY; loadTank(); }); }
|
||||||
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;
|
||||||
@@ -1886,6 +1894,9 @@
|
|||||||
{ title: '1200×630 · social posts, link previews, group covers', items: [
|
{ title: '1200×630 · social posts, link previews, group covers', items: [
|
||||||
{ file: 'ls-social-a.jpg', size: '1200×630 · one link, every page you promote · Join free' },
|
{ file: 'ls-social-a.jpg', size: '1200×630 · one link, every page you promote · Join free' },
|
||||||
{ file: 'ls-social-b.jpg', size: '1200×630 · paid the moment they buy · Join free' } ] },
|
{ file: 'ls-social-b.jpg', size: '1200×630 · paid the moment they buy · Join free' } ] },
|
||||||
|
{ title: '600×300 · traffic exchanges, splash pages, safelist mailers', items: [
|
||||||
|
{ file: 'ls-wide-a.png', size: '600×300 · one link, every page you promote · Join free' },
|
||||||
|
{ file: 'ls-wide-b.png', size: '600×300 · paid the moment they buy · Join free' } ] },
|
||||||
{ title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [
|
{ title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [
|
||||||
{ file: 'ls-square.jpg', size: '1080×1080 · square' },
|
{ file: 'ls-square.jpg', size: '1080×1080 · square' },
|
||||||
{ file: 'ls-story.jpg', size: '1080×1920 · story / reel' } ] },
|
{ file: 'ls-story.jpg', size: '1080×1920 · story / reel' } ] },
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
host.appendChild(box);
|
host.appendChild(box);
|
||||||
var list = FALLBACK, ref = arrivedRef();
|
var list = FALLBACK, ref = arrivedRef();
|
||||||
var paint = function () {
|
var paint = function () {
|
||||||
box.innerHTML = '<span style="flex-basis:100%">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
|
box.innerHTML = '<span style="flex-basis:100%">© 2026 TrustClickz</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
|
||||||
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(withRef(s, ref)) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
||||||
}).join('');
|
}).join('');
|
||||||
};
|
};
|
||||||
@@ -36,3 +36,6 @@
|
|||||||
}
|
}
|
||||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// Network Weekend ribbon (Marty 2026-11-17): netweekend.js paints it only while a network event is live (dates from the hub)
|
||||||
|
(function () { try { if (window.__nwRibbon || document.querySelector('script[src^="/assets/netweekend.js"]')) return; var s = document.createElement('script'); s.src = '/assets/netweekend.js?v=20261117a'; s.defer = true; s.setAttribute('data-site', 'linkspin'); (document.head || document.documentElement).appendChild(s); } catch (e) {} })();
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// "Network Weekend" ribbon (Marty 2026-11-17): a thin bar at the top of every network site page while a network event is live.
|
||||||
|
// Data: /api/network-deals (netdeals.js, from the hub). Switches on and off by this page's own clock at the event's exact
|
||||||
|
// startsAt / endsAt (US Central midnights), so a cached feed never shows it early or late, and it takes itself down at endsAt on
|
||||||
|
// a page left open. Shows this site's own deal for today (byDay, Central date) and links to the full deals page.
|
||||||
|
// The same file lives in every network site. Never RM Circle, never the games. No inline styles (CSP): styles go through CSSOM.
|
||||||
|
// Test clock: window.__NW_NOW (ms) before this script runs; nothing else.
|
||||||
|
(function () {
|
||||||
|
if (window.__nwRibbon) return; window.__nwRibbon = 1;
|
||||||
|
var tag = document.currentScript;
|
||||||
|
var meAttr = (tag && tag.getAttribute('data-site')) || '';
|
||||||
|
function now() { return typeof window.__NW_NOW === 'number' ? window.__NW_NOW : Date.now(); }
|
||||||
|
// late November is CST (UTC-6) for every date this ribbon covers
|
||||||
|
function ctDay(ms) { return new Date(ms - 6 * 3600 * 1000).toISOString().slice(0, 10); }
|
||||||
|
function closedKey(id, day) { return 'nw.closed.' + id + '.' + day; }
|
||||||
|
function isClosed(id, day) { try { return window.localStorage.getItem(closedKey(id, day)) === '1'; } catch (e) { return false; } }
|
||||||
|
function setClosed(id, day) { try { window.localStorage.setItem(closedKey(id, day), '1'); } catch (e) {} }
|
||||||
|
var bar = null;
|
||||||
|
function remove() { if (bar && bar.parentNode) bar.parentNode.removeChild(bar); bar = null; }
|
||||||
|
function paint(body) {
|
||||||
|
var me = meAttr || (body && body.self) || '';
|
||||||
|
var t = now();
|
||||||
|
var ev = ((body && body.events) || []).filter(function (e) { return t >= Date.parse(e.startsAt) && t < Date.parse(e.endsAt); })[0];
|
||||||
|
if (!ev) { remove(); return false; }
|
||||||
|
var day = ctDay(t);
|
||||||
|
if (isClosed(ev.id, day)) { remove(); return true; }
|
||||||
|
var mine = (ev.deals || []).filter(function (d) { return d.site === me && t < Date.parse(d.endsAt || ev.endsAt); })[0];
|
||||||
|
var line = mine ? ((mine.byDay && mine.byDay[day]) || mine.text) : '';
|
||||||
|
var label = (ev.days && ev.days[day]) || '';
|
||||||
|
var onDealsPage = ev.url && (location.origin + location.pathname) === ev.url;
|
||||||
|
remove();
|
||||||
|
bar = document.createElement('div');
|
||||||
|
bar.className = 'nw-ribbon'; bar.setAttribute('role', 'region'); bar.setAttribute('aria-label', ev.name);
|
||||||
|
bar.style.cssText = 'position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px 12px;align-items:center;justify-content:center;padding:8px 40px 8px 16px;'
|
||||||
|
+ 'background:#14161b;color:#f4f1e8;font:600 13.5px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;text-align:center;border-bottom:2px solid #f2c94c';
|
||||||
|
// built node by node with CSSOM styles: no style attributes, so a strict CSP (style-src 'self') has nothing to block
|
||||||
|
function el(tagName, css, text) { var n = document.createElement(tagName); if (css) n.style.cssText = css; if (text) n.textContent = text; return n; }
|
||||||
|
var head = el('span'); head.appendChild(el('b', 'color:#f2c94c', ev.name)); if (label) head.appendChild(document.createTextNode(' · ' + label));
|
||||||
|
bar.appendChild(head);
|
||||||
|
var body2 = el('span', 'font-weight:500', line || ev.tagline);
|
||||||
|
if (line && mine && mine.note) { body2.appendChild(document.createTextNode(' ')); body2.appendChild(el('span', 'opacity:.75', mine.note)); }
|
||||||
|
bar.appendChild(body2);
|
||||||
|
if (ev.url && !onDealsPage) { var a = el('a', 'color:#f2c94c;text-decoration:underline', 'See every deal'); a.href = ev.url; a.target = '_blank'; a.rel = 'noopener'; bar.appendChild(a); }
|
||||||
|
var x = el('button', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:0;color:#f4f1e8;font-size:18px;line-height:1;cursor:pointer;padding:4px 8px', '×');
|
||||||
|
x.type = 'button'; x.setAttribute('aria-label', 'Hide for today'); bar.appendChild(x);
|
||||||
|
bar.querySelector('button').addEventListener('click', function () { setClosed(ev.id, day); remove(); });
|
||||||
|
document.body.insertBefore(bar, document.body.firstChild);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var feed = null, timer = null;
|
||||||
|
function schedule() {
|
||||||
|
clearTimeout(timer); if (!feed) return;
|
||||||
|
// wake at the next switch moment (start, end, a deal ending, the next Central midnight), at least once a minute
|
||||||
|
var t = now(), next = t + 60 * 1000;
|
||||||
|
(feed.events || []).forEach(function (e) {
|
||||||
|
[e.startsAt, e.endsAt].concat((e.deals || []).map(function (d) { return d.endsAt; })).forEach(function (s) { var x = Date.parse(s); if (x > t && x < next) next = x; });
|
||||||
|
});
|
||||||
|
timer = setTimeout(function () { if (typeof window.__NW_NOW === 'number') window.__NW_NOW += next - t; paint(feed); schedule(); }, Math.max(250, next - t));
|
||||||
|
}
|
||||||
|
function run() {
|
||||||
|
fetch('/api/network-deals', { credentials: 'omit' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (b) {
|
||||||
|
if (!b || !Array.isArray(b.events) || !b.events.length) return;
|
||||||
|
feed = b; paint(b); schedule();
|
||||||
|
}).catch(function () {});
|
||||||
|
}
|
||||||
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||||
|
window.__nwPaint = function (b) { feed = b; return paint(b); }; // tests
|
||||||
|
})();
|
||||||
@@ -88,6 +88,7 @@
|
|||||||
// pasted provider forms: say at paste time which autoresponder the form posts to
|
// pasted provider forms: say at paste time which autoresponder the form posts to
|
||||||
+ (k === 'formEmbed' ? '<div class="muted" id="providerNote" style="font-size:12px" hidden></div>' : '')).join('');
|
+ (k === 'formEmbed' ? '<div class="muted" id="providerNote" style="font-size:12px" hidden></div>' : '')).join('');
|
||||||
if ($('imgUpload')) { $('imgUpload').addEventListener('click', () => $('imgFile').click()); $('imgFile').addEventListener('change', () => { uploadFile($('imgFile').files[0]); $('imgFile').value = ''; }); drawImages(); }
|
if ($('imgUpload')) { $('imgUpload').addEventListener('click', () => $('imgFile').click()); $('imgFile').addEventListener('change', () => { uploadFile($('imgFile').files[0]); $('imgFile').value = ''; }); drawImages(); }
|
||||||
|
aiHeadline(p);
|
||||||
if ($('f-formEmbed')) { const fe = $('f-formEmbed'); const upd = () => providerNote(fe.value); fe.addEventListener('input', upd); fe.addEventListener('paste', () => setTimeout(upd, 0)); upd(); }
|
if ($('f-formEmbed')) { const fe = $('f-formEmbed'); const upd = () => providerNote(fe.value); fe.addEventListener('input', upd); fe.addEventListener('paste', () => setTimeout(upd, 0)); upd(); }
|
||||||
// the Look panel: niche preset, design, colours, layout. Each change saves at once and the gallery/preview refresh.
|
// the Look panel: niche preset, design, colours, layout. Each change saves at once and the gallery/preview refresh.
|
||||||
const d = p.design || {}; const setLook = async patch => { try { await api('/api/my/pages/' + p.id, patch); load(true); } catch (e) { toast(e.message, true); } };
|
const d = p.design || {}; const setLook = async patch => { try { await api('/api/my/pages/' + p.id, patch); load(true); } catch (e) { toast(e.message, true); } };
|
||||||
@@ -101,6 +102,31 @@
|
|||||||
$('layouts').querySelectorAll('button').forEach(b => b.addEventListener('click', () => setLook({ layout: b.dataset.l })));
|
$('layouts').querySelectorAll('button').forEach(b => b.addEventListener('click', () => setLook({ layout: b.dataset.l })));
|
||||||
if (!quiet && window.matchMedia('(max-width:900px)').matches) $('side').scrollIntoView({ behavior: 'smooth' });
|
if (!quiet && window.matchMedia('(max-width:900px)').matches) $('side').scrollIntoView({ behavior: 'smooth' });
|
||||||
}
|
}
|
||||||
|
// the AI ad writer on the headline (Marty 2026-11-17): the network hub reads the button link (or the scanned page) and suggests
|
||||||
|
// 3 headline + subhead pairs written only from it; picking one fills both fields to edit. Saved only with Save.
|
||||||
|
let AIW = null;
|
||||||
|
async function aiHeadline(p) {
|
||||||
|
const sub = $('f-sub'); if (!sub) return;
|
||||||
|
if (AIW === null) { try { const w = await CR.get('/api/my/adwriter'); AIW = !!(w && w.on); } catch (e) { AIW = false; } }
|
||||||
|
if (!AIW || !$('f-sub') || $('aiHead')) return;
|
||||||
|
const wrap = document.createElement('div'); wrap.id = 'aiHead'; wrap.style.margin = '0 0 10px';
|
||||||
|
wrap.innerHTML = '<button class="btn sm" type="button" id="aiHeadBtn">Write my headline from my link</button> <span class="muted" style="font-size:11px">Reads the Button link page and suggests 3 headlines with a subhead, using only what that page says.</span><div id="aiHeadList" hidden style="margin-top:8px"></div>';
|
||||||
|
$('f-sub').closest('label').after(wrap);
|
||||||
|
let opts = [];
|
||||||
|
$('aiHeadBtn').addEventListener('click', async () => {
|
||||||
|
const box = $('aiHeadList'); box.hidden = false;
|
||||||
|
const url = (($('f-ctaUrl') && $('f-ctaUrl').value) || (p.scan && p.scan.url) || '').trim();
|
||||||
|
if (!/^https?:\/\/\S+\.\S+/i.test(url)) { box.innerHTML = '<span class="muted">Put the offer link in the Button link field first (starting with https://), then tap the button again.</span>'; return; }
|
||||||
|
$('aiHeadBtn').disabled = true; box.innerHTML = '<span class="muted">Reading the page and writing 3 headlines. This takes a few seconds...</span>';
|
||||||
|
let r; try { r = await api('/api/my/adwriter', { url, kind: 'page' }); } catch (e) { r = { error: e.message || 'The ad writer did not answer. Try again in a minute.' }; }
|
||||||
|
$('aiHeadBtn').disabled = false;
|
||||||
|
if (r.error) { box.innerHTML = '<span class="bad">' + esc(r.error) + '</span>'; return; }
|
||||||
|
opts = r.options || [];
|
||||||
|
box.innerHTML = '<div class="muted" style="font-size:11px;margin-bottom:6px">Tap one to use it, then Save. Check every word is true for your offer.' + (typeof r.left === 'number' ? ' Writes left today: ' + r.left + '.' : '') + '</div>'
|
||||||
|
+ opts.map((o, i) => '<button type="button" class="btn ghost" data-ai="' + i + '" style="display:block;width:100%;text-align:left;margin:0 0 6px;white-space:normal;height:auto"><b>' + esc(o.headline) + '</b><br><span class="muted">' + esc(o.line || '') + '</span></button>').join('');
|
||||||
|
box.querySelectorAll('button[data-ai]').forEach(b => b.addEventListener('click', () => { const o = opts[Number(b.dataset.ai)]; $('f-headline').value = o.headline; if ($('f-sub')) $('f-sub').value = o.line || ''; box.hidden = true; toast('Filled in. Edit it as you like, then tap Save.'); }));
|
||||||
|
});
|
||||||
|
}
|
||||||
function collect(p) { const g = k => { const el = $('f-' + k); return el ? el.value : undefined; }; const c = {}; for (const [k] of F[p.type]) { if (k === 'ctaText' || k === 'ctaUrl') continue; c[k] = g(k); } c.cta = { text: g('ctaText'), url: g('ctaUrl') }; for (const k of ['bullets', 'pros', 'cons']) if (c[k] != null) c[k] = c[k].split('\n'); return c; }
|
function collect(p) { const g = k => { const el = $('f-' + k); return el ? el.value : undefined; }; const c = {}; for (const [k] of F[p.type]) { if (k === 'ctaText' || k === 'ctaUrl') continue; c[k] = g(k); } c.cta = { text: g('ctaText'), url: g('ctaUrl') }; for (const k of ['bullets', 'pros', 'cons']) if (c[k] != null) c[k] = c[k].split('\n'); return c; }
|
||||||
$('edSave').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p), title: ($('f-headline').value || p.title).slice(0, 100) }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } });
|
$('edSave').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p), title: ($('f-headline').value || p.title).slice(0, 100) }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } });
|
||||||
$('edPublish').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p) }); const r = await api('/api/my/pages/' + p.id, { status: p.status === 'published' ? 'draft' : 'published' }); toast(r.page.status === 'published' ? 'Live at ' + pageUrl(r.page) : 'Unpublished'); load(true); } catch (e) { toast(e.message, true); } });
|
$('edPublish').addEventListener('click', async () => { const p = PAGES.find(x => x.id === SEL); if (!p) return; try { await api('/api/my/pages/' + p.id, { content: collect(p) }); const r = await api('/api/my/pages/' + p.id, { status: p.status === 'published' ? 'draft' : 'published' }); toast(r.page.status === 'published' ? 'Live at ' + pageUrl(r.page) : 'Unpublished'); load(true); } catch (e) { toast(e.message, true); } });
|
||||||
|
|||||||
@@ -8,6 +8,9 @@
|
|||||||
var lsid = /^[a-z0-9]{6,20}$/i.test(P.lsid || '') ? P.lsid : '';
|
var lsid = /^[a-z0-9]{6,20}$/i.test(P.lsid || '') ? P.lsid : '';
|
||||||
document.querySelectorAll('a[data-cta]').forEach(function (a) {
|
document.querySelectorAll('a[data-cta]').forEach(function (a) {
|
||||||
try { var u = new URL(a.href); for (var k in P) if (!u.searchParams.has(k)) u.searchParams.set(k, P[k]); a.href = u.toString(); } catch (e) {}
|
try { var u = new URL(a.href); for (var k in P) if (!u.searchParams.has(k)) u.searchParams.set(k, P[k]); a.href = u.toString(); } catch (e) {}
|
||||||
|
// inside the ad viewer (a sandboxed frame with no top navigation) the button opens a new tab: an offer that refuses framing
|
||||||
|
// (X-Frame-Options: DENY) otherwise shows "refused to connect" in the frame (2026-11-23). Opened directly, the page is unchanged.
|
||||||
|
try { if (window.top !== window) { a.target = '_blank'; a.rel = 'noopener'; } } catch (e) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||||
a.addEventListener('click', function () { try { navigator.sendBeacon('/api/p/' + slug + '/hit', new Blob([JSON.stringify({ k: 'cta' })], { type: 'application/json' })); } catch (e) {} });
|
a.addEventListener('click', function () { try { navigator.sendBeacon('/api/p/' + slug + '/hit', new Blob([JSON.stringify({ k: 'cta' })], { type: 'application/json' })); } catch (e) {} });
|
||||||
});
|
});
|
||||||
// the built-in form (.ls-form) usually arrives with the lsid filled by the server; this is the fallback. A pasted
|
// the built-in form (.ls-form) usually arrives with the lsid filled by the server; this is the fallback. A pasted
|
||||||
|
|||||||
@@ -197,3 +197,10 @@ button,input,select,textarea{font:inherit;color:inherit}
|
|||||||
|
|
||||||
/* JetBrains Mono joins "//" into a ligature that reads as a missing slash in URLs (Marty 2026-10-07): no ligatures anywhere */
|
/* JetBrains Mono joins "//" into a ligature that reads as a missing slash in URLs (Marty 2026-10-07): no ligatures anywhere */
|
||||||
body,input,textarea,button,code,.mono{font-variant-ligatures:none;font-feature-settings:"liga" 0,"calt" 0}
|
body,input,textarea,button,code,.mono{font-variant-ligatures:none;font-feature-settings:"liga" 0,"calt" 0}
|
||||||
|
/* how-it-works walkthrough link + player (2026-11-18) */
|
||||||
|
.watchp{margin:12px 0 0}
|
||||||
|
.watchlink{display:inline-flex;align-items:center;gap:8px;font-weight:700;font-size:14.5px;color:var(--accent);text-decoration:underline;text-underline-offset:3px}
|
||||||
|
.watchlink svg{flex:none}
|
||||||
|
.howvid{max-width:980px;width:100%}
|
||||||
|
.howvid video{display:block;width:100%;height:auto;aspect-ratio:16/9;border-radius:8px;border:1px solid var(--line);background:#0B1424}
|
||||||
|
.howvid .note{margin:10px 0 0}
|
||||||
|
|||||||
@@ -748,6 +748,18 @@ img{max-width:100%}
|
|||||||
.pipe-due{display:grid;gap:6px}
|
.pipe-due{display:grid;gap:6px}
|
||||||
.pipe-due .pipe-card{margin:0}
|
.pipe-due .pipe-card{margin:0}
|
||||||
@media (max-width:640px){.pipe-form{grid-template-columns:1fr !important}.pipe-col{flex-basis:200px}}
|
@media (max-width:640px){.pipe-form{grid-template-columns:1fr !important}.pipe-col{flex-basis:200px}}
|
||||||
|
/* the pipeline board fits on one screen (2026-11-20, a member: "need a bottom slide rule so we can see the entire window to the right
|
||||||
|
without having to reduce the size"): a long column scrolls inside itself with its heading pinned, so the board's own sideways
|
||||||
|
scrollbar stays in view; both scrollbars are wide and visible instead of the thin overlay ones */
|
||||||
|
.pipe-col{max-height:min(68vh,760px);overflow-y:auto;overflow-x:hidden}
|
||||||
|
.pipe-col h4{position:sticky;top:-10px;z-index:1;background:inherit;margin:-10px -10px 2px;padding:10px 10px 2px}
|
||||||
|
.pipe-board{scrollbar-width:auto;scrollbar-color:var(--mint) transparent}
|
||||||
|
.pipe-col{scrollbar-width:thin}
|
||||||
|
.pipe-board::-webkit-scrollbar{height:14px}
|
||||||
|
.pipe-board::-webkit-scrollbar-thumb{background:var(--mint);border-radius:8px;border:3px solid transparent;background-clip:padding-box}
|
||||||
|
.pipe-board::-webkit-scrollbar-track{background:var(--line);border-radius:8px}
|
||||||
|
.pipe-col::-webkit-scrollbar{width:8px}
|
||||||
|
.pipe-col::-webkit-scrollbar-thumb{background:var(--line);border-radius:6px}
|
||||||
|
|
||||||
/* ── LinkSpin identity: sapphire + chrome, after the Nexus badge (Marty, 2026-09-16) ──
|
/* ── LinkSpin identity: sapphire + chrome, after the Nexus badge (Marty, 2026-09-16) ──
|
||||||
Deep navy ground, electric-blue accent, brushed-silver headline highlights, circuit-line
|
Deep navy ground, electric-blue accent, brushed-silver headline highlights, circuit-line
|
||||||
@@ -818,3 +830,19 @@ nav .links a.active{color:var(--ink);background:var(--mint-soft-2);box-shadow:in
|
|||||||
:root[data-theme="light"] body::before{opacity:.6}
|
:root[data-theme="light"] body::before{opacity:.6}
|
||||||
:root[data-theme="light"] .ghost{background:linear-gradient(180deg,rgba(23,95,216,.22),transparent 78%);-webkit-background-clip:text;background-clip:text}
|
:root[data-theme="light"] .ghost{background:linear-gradient(180deg,rgba(23,95,216,.22),transparent 78%);-webkit-background-clip:text;background-clip:text}
|
||||||
:root[data-theme="light"] .mockup,:root[data-theme="light"] .modal-card,:root[data-theme="light"] #status,:root[data-theme="light"] #iapChatPanel,:root[data-theme="light"] .chat-drawer{box-shadow:0 18px 50px -20px rgba(15,27,46,.35)}
|
:root[data-theme="light"] .mockup,:root[data-theme="light"] .modal-card,:root[data-theme="light"] #status,:root[data-theme="light"] #iapChatPanel,:root[data-theme="light"] .chat-drawer{box-shadow:0 18px 50px -20px rgba(15,27,46,.35)}
|
||||||
|
/* ── holding-tank readiness (2026-11-18): stage chip, heat with its band, last action, how they got here. Theme tokens only. ── */
|
||||||
|
.rd-line{display:flex;flex-wrap:wrap;gap:4px 6px;align-items:center;margin-top:4px;font-weight:400;white-space:normal}
|
||||||
|
.rd-stage,.rd-heat{display:inline-block;font-size:11px;line-height:1.5;padding:0 7px;border-radius:999px;border:1px solid var(--line-strong);color:var(--muted);font-weight:600;font-variant-numeric:tabular-nums}
|
||||||
|
.rd-s-warming{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)}
|
||||||
|
.rd-s-engaged{color:var(--violet);border-color:var(--violet-line);background:var(--violet-soft)}
|
||||||
|
.rd-s-activated{color:var(--mint);border-color:var(--mint-line);background:var(--mint-soft)}
|
||||||
|
.rd-s-ready{color:var(--ok,#22c55e);border-color:var(--ok,#22c55e);background:var(--ok-soft,rgba(34,197,94,.15))}
|
||||||
|
.rd-hot{color:var(--bad);border-color:var(--bad);background:var(--bad-soft,rgba(255,143,125,.12))}
|
||||||
|
.rd-warm{color:var(--amber);border-color:var(--amber-line);background:var(--amber-soft)}
|
||||||
|
.rd-cooling{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)}
|
||||||
|
.rd-cold{color:var(--muted);border-color:var(--muted-line,var(--line-strong));background:var(--muted-soft)}
|
||||||
|
.rd-last{font-size:11.5px;color:var(--muted)}
|
||||||
|
.rd-entry{display:block;font-size:11.5px;color:var(--muted);font-weight:400;white-space:normal;margin-top:2px}
|
||||||
|
.lin-row .em .rd-line,.lin-row .em .rd-entry{white-space:normal}
|
||||||
|
.lin-row.rd-row .em{white-space:normal}
|
||||||
|
.rd-bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:0 0 8px}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// Holding-tank readiness on the tank cards (Marty 2026-11-18, stage 1 of the tank warm-up). The server attaches `rd` to each waiting
|
||||||
|
// lead from the network hub: { entry: {reason, site, at, detail}, stage, heat: {score, band, label, trend}, last: {kind, site, at} }.
|
||||||
|
// A lead without `rd` (the hub is down) renders exactly as before. Shared by InstantAdPay and LinkSpin (same file in both).
|
||||||
|
(function () {
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
|
const SITES = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners',
|
||||||
|
vbb: 'ViralBannerBlitz', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', fivex: '5xYourTeam', dh: 'DownlineHydra', downlinehydra: 'DownlineHydra', hydra: 'DownlineHydra',
|
||||||
|
ypb: 'YourProgramBuilder', yourprogrambuilder: 'YourProgramBuilder', vas: 'ViralAdSource', viraladsource: 'ViralAdSource', ctb: 'CryptoTeamBuild',
|
||||||
|
stackpol: 'Stack POL', earnerscorner: 'Earners Corner', polhunter: 'PolHunter', btc4hits: 'BTC4Hits' };
|
||||||
|
const site = s => (s ? SITES[String(s).toLowerCase()] || String(s) : '');
|
||||||
|
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||||
|
const day = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getDate() + (d.getFullYear() !== new Date().getFullYear() ? ', ' + d.getFullYear() : ''); };
|
||||||
|
const month = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getFullYear(); };
|
||||||
|
const ago = t => { if (!t) return ''; const ms = Date.now() - t; if (ms < 3600e3) return Math.max(1, Math.round(ms / 60e3)) + ' min ago'; if (ms < 86400e3) return Math.round(ms / 3600e3) + 'h ago'; const d = Math.floor(ms / 86400e3); return d === 1 ? 'yesterday' : d + ' days ago'; };
|
||||||
|
const who = d => (d && d.from ? ' @' + d.from : '');
|
||||||
|
|
||||||
|
function entryText(e) {
|
||||||
|
if (!e || !e.reason || e.reason === 'unknown') return 'How they got here: unknown';
|
||||||
|
const d = e.detail || {};
|
||||||
|
switch (e.reason) {
|
||||||
|
case 'joined': {
|
||||||
|
const src = [d.via ? 'via ' + d.via : '', d.ref && d.ref !== 'direct' ? 'from ' + d.ref : d.ref === 'direct' ? 'typed in directly' : ''].filter(Boolean).join(', ');
|
||||||
|
return 'Joined ' + (site(e.site) || 'the network') + ' ' + day(e.at) + ' with no sponsor' + (src ? ' (' + src + ')' : '');
|
||||||
|
}
|
||||||
|
case 'imported': return 'Imported old member of ' + (site(d.oldSite) || 'an older network site') + (d.memberSince ? ', member since ' + month(d.memberSince) : '') + (d.lastSeenOld ? ', last seen there ' + month(d.lastSeenOld) : '') + (e.at ? ' (in the tank since ' + day(e.at) + ')' : '');
|
||||||
|
case 'rescued': return 'Moved here ' + day(e.at) + ': their sponsor' + who(d) + ' did not reach them in 14 days';
|
||||||
|
case 'released': return d.note ? 'Released ' + day(e.at) + ' by' + (who(d) || ' the member') + ' who had adopted them' : 'Released by their sponsor' + who(d) + ' ' + day(e.at);
|
||||||
|
case 'sponsor_gone': return 'Their sponsor left or was blocked (in the tank since ' + day(e.at) + ')';
|
||||||
|
case 'returned': return 'Back in the tank ' + day(e.at) + ': an adoption' + (d.from ? ' by @' + d.from : '') + ' ended before they got started';
|
||||||
|
default: return 'How they got here: unknown';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const STAGE = { new: ['New', 'Nothing yet beyond joining'], warming: ['Warming', 'Visited or clicked a tracked link'], engaged: ['Engaged', 'Signed in or replied'], activated: ['Activated', 'Wallet linked'], ready: ['Ready', 'Bought something'] };
|
||||||
|
const VERB = { signin: 'signed in', visit: 'visited', click: 'clicked a tracked link', wallet: 'linked a wallet', purchase: 'bought a package', upgrade: 'upgraded', message: 'replied to a message', share: 'shared a link' };
|
||||||
|
function lastText(l) {
|
||||||
|
if (!l) return 'no activity yet';
|
||||||
|
return (VERB[l.kind] || l.kind) + (l.site ? ' on ' + site(l.site) : '') + ', ' + ago(l.at);
|
||||||
|
}
|
||||||
|
// the block that goes under the lead's name: stage chip, heat, last action, entry reason
|
||||||
|
function html(rd) {
|
||||||
|
if (!rd) return '';
|
||||||
|
const st = STAGE[rd.stage] || STAGE.new; const h = rd.heat || { score: 0, band: 'cold', label: 'Cold' };
|
||||||
|
const tr = h.trend === 'up' ? ' ↗' : h.trend === 'down' ? ' ↘' : '';
|
||||||
|
return '<span class="rd-line"><span class="rd-stage rd-s-' + esc(rd.stage) + '" title="' + esc(st[1]) + '">' + esc(st[0]) + '</span>'
|
||||||
|
+ '<span class="rd-heat rd-' + esc(h.band) + '" title="Heat 0-100 from real actions across the network, recent ones count most. Hot 70+, Warm 40-69, Cooling 15-39, Cold under 15.">' + Number(h.score || 0) + ' · ' + esc(h.label || '') + tr + '</span>'
|
||||||
|
+ '<span class="rd-last" title="Their newest real action on the network">' + esc(lastText(rd.last)) + '</span></span>'
|
||||||
|
+ '<span class="rd-entry">' + esc(entryText(rd.entry)) + '</span>';
|
||||||
|
}
|
||||||
|
const score = m => (m && m.rd && m.rd.heat ? Number(m.rd.heat.score) || 0 : -1);
|
||||||
|
window.TankReady = { html, entryText, lastText, score, stageLabel: s => (STAGE[s] || STAGE.new)[0] };
|
||||||
|
})();
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// Video Spin (2026-11-22): the third view on the Links screen. One short link that rotates through video pages on Social Tube.
|
||||||
|
// It is a spin link underneath (rotator.js, kind 'video'): pause, weights and removal go through the spin-link routes; creating one,
|
||||||
|
// adding videos and the play counts go through /api/my/videospins (server.js), which checks every video with Video App Income.
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
if (!window.CR || !document.getElementById('vsWs')) return;
|
||||||
|
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast;
|
||||||
|
let D = null, SPINS = [], SEL = null, HOST = '', PLAYS = {}, BUSY = false;
|
||||||
|
let WANT = Number((/^#v([0-9]+)$/.exec(location.hash) || [])[1]) || 0; // the Video Spin named in the address when the page opened
|
||||||
|
const mark = () => { if (!$('vsWs').hidden) history.replaceState(null, '', '#v' + (SEL || '')); };
|
||||||
|
const base = () => 'https://' + (HOST || location.host), linkOf = s => base() + '/r/' + s.code;
|
||||||
|
const clicks7 = s => s.hits7 || 0;
|
||||||
|
const zoneCode = s => '<iframe src="' + base() + '/vz/' + s.code + '" width="315" height="560" style="border:0;border-radius:14px;max-width:100%" allow="fullscreen" allowfullscreen loading="lazy" title="Videos"></iframe>';
|
||||||
|
const state = s => s.paused ? { cls: 'warn', t: 'PAUSED' } : !s.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE VIDEO' } : { cls: 'ok', t: 'LIVE' };
|
||||||
|
|
||||||
|
// ── view switch: this script only owns the Video Spins view; banner-spin.js keeps switching the other two ──
|
||||||
|
function show(on) {
|
||||||
|
$('vsWs').hidden = !on; const vb = $('vsNewBtn'); if (vb) vb.hidden = !on;
|
||||||
|
if (on) { $('ws').hidden = true; $('bsWs').hidden = true; const nb = $('newBtn'), bn = $('bsNewBtn'); if (nb) nb.hidden = true; if (bn) bn.hidden = true; }
|
||||||
|
}
|
||||||
|
$('vsw').querySelectorAll('button').forEach(b => b.addEventListener('click', () => {
|
||||||
|
const on = b.dataset.v === 'videos'; show(on);
|
||||||
|
if (on) load(true);
|
||||||
|
}));
|
||||||
|
(function addBtn(n) { const nb = $('newBtn'); if (!nb) { if (n < 50) setTimeout(() => addBtn(n + 1), 200); return; }
|
||||||
|
const b = document.createElement('button'); b.className = 'btn pri'; b.id = 'vsNewBtn'; b.type = 'button'; b.hidden = $('vsWs').hidden; b.textContent = '+ New Video Spin'; nb.parentNode.appendChild(b);
|
||||||
|
b.addEventListener('click', () => { SEL = null; render(); const i = $('vsNewName'); if (i) i.focus(); }); })(0);
|
||||||
|
|
||||||
|
async function load(keep) {
|
||||||
|
try { D = await CR.get('/api/my/videospins'); } catch (e) { toast(e.message, true); return; }
|
||||||
|
SPINS = (D.spins || []).slice().sort((a, b) => clicks7(b) - clicks7(a) || b.created - a.created);
|
||||||
|
const hs = D.hosts || []; if (!HOST || !hs.includes(HOST)) HOST = hs[0] || location.host;
|
||||||
|
if (!keep || !SPINS.some(s => s.id === SEL)) SEL = null;
|
||||||
|
if (WANT) { if (SPINS.some(s => s.id === WANT)) SEL = WANT; WANT = 0; }
|
||||||
|
mark(); setTimeout(mark, 1500); // the spin-link list reloads in the background and may set its own address; keep ours while this view is open
|
||||||
|
render(); if (SEL) loadPlays();
|
||||||
|
}
|
||||||
|
async function loadPlays() { const id = SEL; try { const r = await CR.get('/api/my/videospins/' + id + '/plays'); if (id === SEL) { PLAYS = r.plays || {}; renderDetail(); } } catch (e) {} }
|
||||||
|
|
||||||
|
function render() { renderList(); renderDetail(); }
|
||||||
|
function renderList() {
|
||||||
|
const L = D.limits || { spins: 0, videos: 0 }, t = D.tier || { label: '' };
|
||||||
|
$('vsCount').textContent = SPINS.length + ' Video Spin' + (SPINS.length === 1 ? '' : 's');
|
||||||
|
$('vsTier').innerHTML = L.spins ? esc(t.label) + ' tier: ' + L.spins + ' Video Spins, ' + L.videos + ' videos in each.'
|
||||||
|
: 'Video Spins start at the Starter tier (any package of your own): 2 Video Spins with 5 videos in each.';
|
||||||
|
$('vsItems').innerHTML = SPINS.length ? SPINS.map(s => { const h = state(s); return '<div class="item' + (s.id === SEL ? ' on' : '') + '" data-id="' + s.id + '" role="button" tabindex="0">'
|
||||||
|
+ '<div><div class="nm">' + esc(s.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + ' <span class="tag plain">' + s.destinations.length + ' video' + (s.destinations.length === 1 ? '' : 's') + '</span></div><div class="cd">' + esc((HOST || location.host) + '/r/' + s.code) + '</div></div>'
|
||||||
|
+ '<div class="rt"><span class="n">' + fmt(clicks7(s)) + '</span><span class="muted" style="font-size:10px">7 d</span></div></div>'; }).join('')
|
||||||
|
: '<div class="empty"><div class="muted">No Video Spins yet.</div></div>';
|
||||||
|
$('vsItems').querySelectorAll('.item').forEach(el => { const go = () => { SEL = Number(el.dataset.id); PLAYS = {}; history.replaceState(null, '', '#v' + SEL); render(); loadPlays(); };
|
||||||
|
el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDetail() {
|
||||||
|
const box = $('vsDetail'), s = SPINS.find(x => x.id === SEL), L = D.limits || { spins: 0, videos: 0 };
|
||||||
|
if (!s) {
|
||||||
|
const can = D.on && L.spins > 0 && SPINS.length < L.spins;
|
||||||
|
box.innerHTML = '<div class="vsp"><div class="h-disp" style="font-size:18px">Video Spin</div>'
|
||||||
|
+ '<p class="muted" style="margin:8px 0 14px;max-width:560px">One short link that plays a different video page each time it is opened. Pick videos you made on Video App Income, or add any member\'s video by its Social Tube link. Share the one link; the videos take turns. People who go on to make their own video are credited to you.</p>'
|
||||||
|
+ '<details id="vsHow" style="margin:0 0 14px;max-width:640px"><summary style="cursor:pointer;font-weight:600">Watch how this works (1:42)</summary>'
|
||||||
|
+ '<video controls playsinline preload="none" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.jpg?v=20261122a" style="display:block;width:100%;height:auto;background:#000;border-radius:12px;margin-top:10px" aria-label="Video: Marty walks through Video Spins, 1 minute 42 seconds"><source src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/video-spins.mp4?v=20261122a" type="video/mp4"></video></details>'
|
||||||
|
+ (D.vaiError ? '<p class="muted" style="margin:0 0 12px">' + esc(D.vaiError) + '</p>' : '')
|
||||||
|
+ (!D.on ? '<p class="muted">Video Spins are not switched on yet.</p>'
|
||||||
|
: can ? '<div class="vsrow"><input class="field" id="vsNewName" maxlength="80" placeholder="Name this Video Spin, for example: My best videos"><button class="btn pri" type="button" id="vsCreate">Create</button></div>'
|
||||||
|
: '<p class="muted">' + (L.spins ? 'You have all ' + L.spins + ' Video Spins your tier holds. Remove one to make another.' : 'Video Spins start at the Starter tier (any package of your own).') + '</p>')
|
||||||
|
+ '</div>';
|
||||||
|
const c = $('vsCreate'); if (c) { const go = async () => { const name = $('vsNewName').value.trim(); if (!name) { toast('Give it a name first.', true); return; } if (BUSY) return; BUSY = true;
|
||||||
|
try { const r = await api('/api/my/videospins', { name }); SEL = r.rotation.id; history.replaceState(null, '', '#v' + SEL); toast('Video Spin created. Now add videos.'); await load(true); } catch (e) { toast(e.message, true); } BUSY = false; };
|
||||||
|
c.addEventListener('click', go); $('vsNewName').addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const inSpin = new Set(s.destinations.map(d => d.vid)), mine = (D.videos || []).filter(v => !inSpin.has(v.id)), room = Math.max(0, L.videos - s.destinations.length);
|
||||||
|
const rows = s.destinations.map(d => { const p = PLAYS[d.vid] || null, gone = p && p.live === false;
|
||||||
|
const tag = gone ? '<span class="tag bad">REMOVED BY OWNER</span>' : !d.active ? '<span class="tag warn">' + (d.autoPaused ? 'PAUSED: NOT LOADING' : 'PAUSED') + '</span>' : '';
|
||||||
|
return '<div class="vsv"><img src="' + esc(d.poster || '') + '" alt="" loading="lazy"><div class="vsi"><b>' + esc(d.label || 'Video') + '</b> ' + tag + '<div class="muted">' + (d.vowner ? 'By ' + esc(d.vowner) + '. ' : '') + fmt(d.hits || 0) + ' click' + ((d.hits || 0) === 1 ? '' : 's')
|
||||||
|
+ (p ? ', ' + fmt(p.views) + ' opened, ' + fmt(p.plays) + ' played, ' + fmt(p.taps) + ' tapped the button' : '') + '</div></div>'
|
||||||
|
+ '<div class="vsa"><button class="btn sm" type="button" data-act="' + (d.active ? 'pause' : 'resume') + '" data-d="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm" type="button" data-act="remove" data-d="' + d.id + '">Remove</button></div></div>'; }).join('');
|
||||||
|
box.innerHTML = '<div class="vsp"><div class="vshead"><h2>' + esc(s.name) + '</h2><span class="tag ' + state(s).cls + '">' + state(s).t + '</span></div>'
|
||||||
|
+ '<div class="vsrow"><input class="field mono" id="vsLink" readonly value="' + esc(linkOf(s)) + '"><button class="btn pri" type="button" id="vsCopy">Copy link</button><button class="btn" type="button" id="vsPause">' + (s.paused ? 'Resume' : 'Pause') + '</button><button class="btn" type="button" id="vsDel">Delete</button></div>'
|
||||||
|
+ '<p class="muted" style="margin:8px 0 0">' + fmt(s.hits || 0) + ' clicks in all, ' + fmt(s.hits7 || 0) + ' in the last 7 days' + (s.conversions ? ', ' + s.conversions + ' conversion' + (s.conversions === 1 ? '' : 's') : '') + '. Each open goes to one of the videos below.</p>'
|
||||||
|
+ '<details class="vsz"><summary>Put it on a web page (rotating player)</summary><p class="muted" style="margin:8px 0">Paste this code into any page. Each page view plays a different video from this spin, with that video\'s own button. Page views are not counted as clicks; plays and button taps show under each video.</p><textarea class="field mono" id="vsZone" readonly rows="3" style="width:100%">' + esc(zoneCode(s)) + '</textarea><div class="vsrow" style="margin-top:8px"><button class="btn" type="button" id="vsZoneCopy">Copy code</button></div></details>'
|
||||||
|
+ '<h3 class="vsh">Videos in this spin <span class="muted">' + s.destinations.length + ' of ' + L.videos + '</span></h3>'
|
||||||
|
+ (rows || '<p class="muted">No videos yet. Add some below; the link starts working with the first one.</p>')
|
||||||
|
+ '<h3 class="vsh">Add your videos</h3>'
|
||||||
|
+ (D.vaiError ? '<p class="muted">' + esc(D.vaiError) + '</p>' : !D.member ? '<p class="muted">No Video App Income account was found for your email address. Make your first video at <a href="https://linkspin.app/r/nwvai?src=linkspin&s2=" target="_blank" rel="noopener">videoappincome.com</a> (it is free), then come back.</p>'
|
||||||
|
: !room ? '<p class="muted">This Video Spin is full for your tier.</p>'
|
||||||
|
: mine.length ? '<div class="vsgrid">' + mine.map(v => '<label class="vsc"><input type="checkbox" value="' + esc(v.id) + '"><img src="' + esc(v.poster) + '" alt="" loading="lazy"><span>' + esc(v.title) + '</span></label>').join('') + '</div><div class="vsrow" style="margin-top:10px"><button class="btn pri" type="button" id="vsAddMine">Add selected</button><span class="muted">Room for ' + room + ' more.</span></div>'
|
||||||
|
: '<p class="muted">' + ((D.videos || []).length ? 'All of your videos are already in this spin.' : 'You have no videos on Social Tube yet. Make one on Video App Income and it appears here.') + '</p>')
|
||||||
|
+ '<h3 class="vsh">Add any member\'s video</h3><p class="muted" style="margin:0 0 8px">Open the video on socialtube.club and paste its address. Its owner gets the views; people who go on to join are credited to you.</p>'
|
||||||
|
+ (room ? '<div class="vsrow"><input class="field" id="vsLinkIn" maxlength="300" placeholder="https://socialtube.club/watch/..."><button class="btn" type="button" id="vsAddLink">Add</button></div>' : '<p class="muted">This Video Spin is full for your tier.</p>')
|
||||||
|
+ '</div>';
|
||||||
|
$('vsCopy').addEventListener('click', () => { const u = linkOf(s); (navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(u) : Promise.reject()).then(() => toast('Link copied'), () => { $('vsLink').select(); toast('Select and copy the link', true); }); });
|
||||||
|
$('vsZoneCopy').addEventListener('click', () => { const u = zoneCode(s); (navigator.clipboard && navigator.clipboard.writeText ? navigator.clipboard.writeText(u) : Promise.reject()).then(() => toast('Code copied'), () => { $('vsZone').select(); toast('Select and copy the code', true); }); });
|
||||||
|
$('vsPause').addEventListener('click', () => act(() => api('/api/my/rotations/' + s.id, { paused: !s.paused }), s.paused ? 'Resumed' : 'Paused'));
|
||||||
|
$('vsDel').addEventListener('click', e => { const b = e.currentTarget; if (b.dataset.arm !== '1') { b.dataset.arm = '1'; b.textContent = 'Tap again to delete'; setTimeout(() => { b.dataset.arm = ''; b.textContent = 'Delete'; }, 4000); return; }
|
||||||
|
act(async () => { await api('/api/my/rotations/' + s.id, { remove: true }); SEL = null; history.replaceState(null, '', '#v'); }, 'Video Spin deleted'); });
|
||||||
|
box.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => { const a = b.dataset.act, p = '/api/my/rotations/' + s.id + '/dest/' + b.dataset.d;
|
||||||
|
act(() => api(p, a === 'remove' ? { remove: true } : { active: a === 'resume' }), a === 'remove' ? 'Video removed from this spin' : a === 'resume' ? 'Video resumed' : 'Video paused'); }));
|
||||||
|
const am = $('vsAddMine'); if (am) am.addEventListener('click', () => { const ids = [...box.querySelectorAll('.vsc input:checked')].map(x => x.value); if (!ids.length) { toast('Tick at least one video.', true); return; }
|
||||||
|
act(() => api('/api/my/videospins/' + s.id + '/add', { ids }), ids.length === 1 ? 'Video added' : ids.length + ' videos added'); });
|
||||||
|
const al = $('vsAddLink'); if (al) { const go = () => { const link = $('vsLinkIn').value.trim(); if (!link) { toast('Paste a Social Tube video link first.', true); return; } act(() => api('/api/my/videospins/' + s.id + '/add', { link }), 'Video added'); };
|
||||||
|
al.addEventListener('click', go); $('vsLinkIn').addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); }
|
||||||
|
}
|
||||||
|
async function act(fn, done) { if (BUSY) return; BUSY = true; try { await fn(); if (done) toast(done); await load(true); } catch (e) { toast(e.message, true); } BUSY = false; }
|
||||||
|
|
||||||
|
window.VideoSpin = { reload: () => load(true) };
|
||||||
|
if (/^#v/.test(location.hash)) setTimeout(() => { const b = $('vsw').querySelector('button[data-v="videos"]'); if (b) b.click(); }, 400);
|
||||||
|
})();
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.rule{display:grid;grid-template-columns:150px minmax(0,1fr);gap:14px;padding:10px 0;border-bottom:1px solid var(--line);font-size:14px;color:var(--ink-2)}
|
.rule{display:grid;grid-template-columns:150px minmax(0,1fr);gap:14px;padding:10px 0;border-bottom:1px solid var(--line);font-size:14px;color:var(--ink-2)}
|
||||||
.rule:last-child{border-bottom:0}
|
.rule:last-child{border-bottom:0}
|
||||||
@@ -149,6 +149,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/contract.js?v=20261023ov"></script>
|
<script src="/assets/contract.js?v=20261023ov"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.rg{max-width:980px}
|
.rg{max-width:980px}
|
||||||
.rg p{margin:0}
|
.rg p{margin:0}
|
||||||
@@ -284,6 +284,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -70,7 +70,7 @@
|
|||||||
<div id="goalReports"></div>
|
<div id="goalReports"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/conversions.js?v=20261026a"></script>
|
<script src="/assets/conversions.js?v=20261026a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -81,9 +81,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/credits-screen.js?v=20261107tg"></script>
|
<script src="/assets/credits-screen.js?v=20261107tg"></script>
|
||||||
<script src="/assets/fuel.js?v=20261112sso"></script>
|
<script src="/assets/fuel.js?v=20261112sso"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="top">
|
<header class="top">
|
||||||
@@ -47,6 +47,6 @@
|
|||||||
<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/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -69,7 +69,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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+3
-2
@@ -19,6 +19,7 @@
|
|||||||
.hf textarea.field{font:500 14px var(--body, Manrope, system-ui);line-height:1.5;resize:vertical}
|
.hf textarea.field{font:500 14px var(--body, Manrope, system-ui);line-height:1.5;resize:vertical}
|
||||||
.acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
.acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
|
||||||
.hmsg{font-size:12.5px;color:var(--muted)} .hmsg.bad{color:var(--bad)}
|
.hmsg{font-size:12.5px;color:var(--muted)} .hmsg.bad{color:var(--bad)}
|
||||||
|
.hsg{border:1px solid var(--line);border-radius:12px;padding:10px 14px;font-size:13.5px}.hsg-h{margin:0 0 6px}.hsg-h span,.hsg-s{color:var(--muted);font-weight:500}.hsg details{margin:4px 0}.hsg summary{cursor:pointer;font-weight:700}.hsg-b{white-space:pre-wrap;word-wrap:break-word;line-height:1.5;margin:6px 0 8px}
|
||||||
.sup-msg{border:1px solid var(--line);border-radius:8px;padding:12px 14px;background:var(--panel-2)}
|
.sup-msg{border:1px solid var(--line);border-radius:8px;padding:12px 14px;background:var(--panel-2)}
|
||||||
.sup-msg.admin{border-color:var(--accent-dim, #7CB2FF);background:var(--accent-soft, #E1ECFC)}
|
.sup-msg.admin{border-color:var(--accent-dim, #7CB2FF);background:var(--accent-soft, #E1ECFC)}
|
||||||
.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}
|
.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}
|
||||||
@@ -30,7 +31,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=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/help-screen.js?v=20261016a"></script>
|
<script src="/assets/help-screen.js?v=20261116sg"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+12
-2
@@ -21,7 +21,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
@@ -52,6 +52,7 @@
|
|||||||
<span class="check"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>Click ids pass through</span>
|
<span class="check"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>Click ids pass through</span>
|
||||||
<span class="check"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>Your own short domain</span>
|
<span class="check"><svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>Your own short domain</span>
|
||||||
</div>
|
</div>
|
||||||
|
<p class="watchp"><a class="watchlink" href="#watch"><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><circle cx="12" cy="12" r="11" fill="currentColor"/><path d="M10 8l6 4-6 4z" fill="var(--panel)"/></svg>Watch how LinkSpin works</a></p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tile hi demo">
|
<div class="tile hi demo">
|
||||||
@@ -130,6 +131,14 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="sec" id="watch">
|
||||||
|
<div class="wrap">
|
||||||
|
<div class="sec-h"><h2 class="disp">Watch how LinkSpin works</h2><span class="eyebrow">the whole site, step by step</span></div>
|
||||||
|
<div class="tile card howvid"><video controls playsinline preload="none" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/linkspin-tour.jpg?v=20261118a" width="1920" height="1080" aria-describedby="watchNote"><source src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/linkspin-tour.mp4?v=20261118a" type="video/mp4"></video>
|
||||||
|
<p class="note" id="watchNote">A short walkthrough in Marty's voice: one link that rotates your pages, weights and hours, the Share kit, traffic sources, Reports, Pages and Zones, and where to go next. Nothing is promised.</p></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="sec" id="split">
|
<section class="sec" id="split">
|
||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<div class="two">
|
<div class="two">
|
||||||
@@ -225,6 +234,7 @@
|
|||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script src="/assets/home.js?v=20261113me"></script>
|
<script src="/assets/home.js?v=20261113me"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
|
<script src="https://polhunter.com/embed.js" data-slots="3" data-selector="article.tile.card" async></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+3
-3
@@ -10,7 +10,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.spon{display:inline-flex;align-items:center;gap:10px;padding:8px 12px;border:1px solid var(--line);border-radius:999px;background:var(--panel);align-self:flex-start;max-width:100%}
|
.spon{display:inline-flex;align-items:center;gap:10px;padding:8px 12px;border:1px solid var(--line);border-radius:999px;background:var(--panel);align-self:flex-start;max-width:100%}
|
||||||
.spon .av{width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-dim));display:grid;place-items:center;color:var(--accent-ink);font:700 11px var(--mono);overflow:hidden;flex:none}
|
.spon .av{width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-dim));display:grid;place-items:center;color:var(--accent-ink);font:700 11px var(--mono);overflow:hidden;flex:none}
|
||||||
@@ -106,8 +106,8 @@ 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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/join.js?v=20261111b4h"></script>
|
<script src="/assets/join.js?v=20261111b4h"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
+1
-1
@@ -102,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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/launch.js?v=20261105po"></script>
|
<script src="/assets/launch.js?v=20261105po"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+3
-3
@@ -19,7 +19,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="top">
|
<header class="top">
|
||||||
@@ -65,8 +65,8 @@
|
|||||||
<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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/ledger.js?v=20261007a"></script>
|
<script src="/assets/ledger.js?v=20261007a"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+21
-2
@@ -107,11 +107,21 @@
|
|||||||
.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}
|
||||||
@media (max-width:900px){.bsr .ml,.st3 .ml{display:inline;color:var(--muted);font-size:11px}.bsr .rw .r,.st3 .rw .r{text-align:left}.bsr .hd,.st3 .hd{display:none}.bsr .rw{grid-template-columns:1fr 1fr}.st3 .rw{grid-template-columns:1fr 1fr 1fr}.st3 .rw>:first-child{grid-column:1/-1}.addg{grid-template-columns:1fr}.bsbreak{grid-template-columns:1fr}}
|
@media (max-width:900px){.bsr .ml,.st3 .ml{display:inline;color:var(--muted);font-size:11px}.bsr .rw .r,.st3 .rw .r{text-align:left}.bsr .hd,.st3 .hd{display:none}.bsr .rw{grid-template-columns:1fr 1fr}.st3 .rw{grid-template-columns:1fr 1fr 1fr}.st3 .rw>:first-child{grid-column:1/-1}.addg{grid-template-columns:1fr}.bsbreak{grid-template-columns:1fr}}
|
||||||
@media (max-width:760px){.bsr .rw{grid-template-columns:1fr}.tgt{grid-template-columns:1fr}.vsw{padding:8px 10px 0}.vsw button{padding:6px 10px;font-size:14px}}
|
@media (max-width:760px){.bsr .rw{grid-template-columns:1fr}.tgt{grid-template-columns:1fr}.vsw{padding:8px 10px 0}.vsw button{padding:6px 10px;font-size:14px}}
|
||||||
|
/* Video Spin (2026-11-22) */
|
||||||
|
.vsp{padding:18px 20px 28px;max-width:860px}.vshead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px}.vshead h2{margin:0;font-size:20px}
|
||||||
|
.vsrow{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.vsrow .field{flex:1;min-width:200px}
|
||||||
|
.vsh{font-size:14px;letter-spacing:.06em;text-transform:uppercase;margin:24px 0 8px;display:flex;gap:10px;align-items:baseline}.vsh .muted{font-size:12px;text-transform:none;letter-spacing:0;font-weight:400}
|
||||||
|
.vsv{display:grid;grid-template-columns:44px minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 0;border-bottom:1px solid var(--line)}.vsv img{width:44px;height:78px;object-fit:cover;border-radius:6px;background:#000}
|
||||||
|
.vsi b{font-size:14px}.vsi .muted{font-size:12.5px;margin-top:3px}.vsa{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}
|
||||||
|
.vsz{margin-top:14px;border:1px solid var(--line);border-radius:8px;padding:10px 12px;background:var(--panel)}.vsz summary{cursor:pointer;font-weight:700;font-size:13.5px}
|
||||||
|
.vsgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:10px}.vsc{position:relative;display:block;cursor:pointer;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}
|
||||||
|
.vsc img{display:block;width:100%;aspect-ratio:9/16;object-fit:cover;background:#000}.vsc span{display:block;font-size:12px;line-height:1.3;padding:6px 7px;max-height:44px;overflow:hidden}.vsc input{position:absolute;left:6px;top:6px;width:18px;height:18px}
|
||||||
|
@media (max-width:760px){.vsp{padding:14px 14px 24px}.vsv{grid-template-columns:44px minmax(0,1fr)}.vsa{grid-column:1/-1;justify-content:flex-start}}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="page">
|
<div id="page">
|
||||||
<div class="vsw" id="vsw" role="tablist" aria-label="Link type"><button type="button" class="on" data-v="links" role="tab">Spin links</button><button type="button" data-v="banners" role="tab">Banner Spins<span class="nw">NEW</span></button></div>
|
<div class="vsw" id="vsw" role="tablist" aria-label="Link type"><button type="button" class="on" data-v="links" role="tab">Spin links</button><button type="button" data-v="banners" role="tab">Banner Spins<span class="nw">NEW</span></button><button type="button" data-v="videos" role="tab">Video Spins<span class="nw">NEW</span></button></div>
|
||||||
<div class="ws" id="ws">
|
<div class="ws" id="ws">
|
||||||
<div class="list">
|
<div class="list">
|
||||||
<div class="hd"><h2 id="listCount">Links</h2><span class="muted mono" id="listSort">by clicks, 7 days</span></div>
|
<div class="hd"><h2 id="listCount">Links</h2><span class="muted mono" id="listSort">by clicks, 7 days</span></div>
|
||||||
@@ -183,6 +193,14 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="ws" id="vsWs" hidden>
|
||||||
|
<div class="list">
|
||||||
|
<div class="hd"><h2 id="vsCount">Video Spins</h2><span class="muted mono">by clicks, 7 days</span></div>
|
||||||
|
<div class="flt" id="vsTier" style="font-size:12px"></div>
|
||||||
|
<div class="items" id="vsItems"></div>
|
||||||
|
</div>
|
||||||
|
<div class="detail" id="vsDetail"></div>
|
||||||
|
</div>
|
||||||
<div class="ws" id="bsWs" hidden>
|
<div class="ws" id="bsWs" hidden>
|
||||||
<div class="list">
|
<div class="list">
|
||||||
<div class="hd"><h2 id="bsCount">Banner Spins</h2><span class="muted mono" id="bsSort">by views, 30 d</span></div>
|
<div class="hd"><h2 id="bsCount">Banner Spins</h2><span class="muted mono" id="bsSort">by views, 30 d</span></div>
|
||||||
@@ -270,8 +288,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/links.js?v=20261111big"></script>
|
<script src="/assets/links.js?v=20261111big"></script>
|
||||||
<script src="/assets/banner-spin.js?v=20261114bc"></script>
|
<script src="/assets/banner-spin.js?v=20261114bc"></script>
|
||||||
|
<script src="/assets/video-spin.js?v=20261123a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+6
-5
@@ -8,7 +8,7 @@
|
|||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/cr.css?v=20261114tu">
|
<link rel="stylesheet" href="/assets/cr.css?v=20261114tu">
|
||||||
<style>@import url("/assets/site.css?v=ls20261101t") layer(legacy);</style>
|
<style>@import url("/assets/site.css?v=ls20261120pp") layer(legacy);</style>
|
||||||
<link rel="stylesheet" href="/assets/tools.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/tools.css?v=20261101t">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -990,7 +990,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
</main>
|
</main>
|
||||||
<footer class="bo-pagefoot"><span id="navWallet" class="small muted">…</span><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a><a href="#" id="logoutLink">Log out</a><span style="width:100%;text-align:center" class="small muted">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span></footer>
|
<footer class="bo-pagefoot"><span id="navWallet" class="small muted">…</span><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a><a href="#" id="logoutLink">Log out</a><span style="width:100%;text-align:center" class="small muted">© 2026 TrustClickz</span></footer>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div><!-- /page -->
|
</div><!-- /page -->
|
||||||
@@ -1015,12 +1015,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></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=20261114sso"></script>
|
<script src="/assets/tankready.js?v=20261118rd"></script>
|
||||||
|
<script src="/assets/my.js?v=20261118rd"></script>
|
||||||
<script src="/assets/chat.js?v=20261016a"></script>
|
<script src="/assets/chat.js?v=20261016a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -73,7 +73,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/pages-screen.js?v=20261021t"></script>
|
<script src="/assets/pages-screen.js?v=20261117aiw"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -131,8 +131,8 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/partners.js?v=20261010a"></script>
|
<script src="/assets/partners.js?v=20261010a"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/plays.js?v=20260910b"></script>
|
<script src="/assets/plays.js?v=20260910b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -9,7 +9,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="top">
|
<header class="top">
|
||||||
@@ -56,6 +56,6 @@
|
|||||||
<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/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.strip .n{font-family:var(--display);font-size:22px;color:var(--chrome-ink);letter-spacing:.04em;line-height:1}
|
.strip .n{font-family:var(--display);font-size:22px;color:var(--chrome-ink);letter-spacing:.04em;line-height:1}
|
||||||
.strip .st{display:flex;align-items:baseline;gap:8px}
|
.strip .st{display:flex;align-items:baseline;gap:8px}
|
||||||
@@ -289,6 +289,6 @@
|
|||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script src="/assets/publishers.js?v=20261010a"></script>
|
<script src="/assets/publishers.js?v=20261010a"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -20,7 +20,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.rg{max-width:980px}
|
.rg{max-width:980px}
|
||||||
.rg p{margin:0}
|
.rg p{margin:0}
|
||||||
@@ -281,6 +281,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
<script src="/assets/refuel-guide.js?v=20261024rg"></script>
|
<script src="/assets/refuel-guide.js?v=20261024rg"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -90,7 +90,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/reports.js?v=20261107nc"></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=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></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>
|
||||||
|
|||||||
+3
-3
@@ -10,7 +10,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
<style>
|
<style>
|
||||||
.sup{max-width:760px}
|
.sup{max-width:760px}
|
||||||
.sup .tile{padding:0}
|
.sup .tile{padding:0}
|
||||||
@@ -67,8 +67,8 @@
|
|||||||
<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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/support.js?v=20261016a"></script>
|
<script src="/assets/support.js?v=20261016a"></script>
|
||||||
<script src="/assets/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></script>
|
||||||
<script src="/assets/team.js?v=20261113org"></script>
|
<script src="/assets/team.js?v=20261113org"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -9,7 +9,7 @@
|
|||||||
<!--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-->
|
||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700&family=Manrope:wght@400;500;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
<link rel="stylesheet" href="/assets/pub.css?v=20261101t">
|
<link rel="stylesheet" href="/assets/pub.css?v=20261118w">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="top">
|
<header class="top">
|
||||||
@@ -62,6 +62,6 @@
|
|||||||
<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/netline.js?v=20261115nr" data-site="linkspin"></script>
|
<script src="/assets/netline.js?v=20261117nw" data-site="linkspin"></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=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></script>
|
||||||
<script src="/assets/tx.js?v=20260906m"></script>
|
<script src="/assets/tx.js?v=20260906m"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -49,7 +49,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></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>
|
<script src="/assets/wall-founder.js?v=20261105fd"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+1
-1
@@ -36,7 +36,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></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=20261115nr"></script>
|
<script src="/assets/common.js?v=20261117nw"></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=20261114tu"></script>
|
<script src="/assets/cr-shell.js?v=20261115hub"></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,107 @@
|
|||||||
|
// LinkSpin member erase (erase.js + scrub.js, 2026-11-15, ticket LS-1021) in JSON mode on a throwaway DATA_DIR, synthetic members only:
|
||||||
|
// scrub rules, dry run changes nothing, a module's live copy is scrubbed and saved (not overwritten later), plain documents
|
||||||
|
// and JSON Lines through the fs layer, their spin links (rotator.eraseOwner), the tombstone, blockers + force, the hub's
|
||||||
|
// member.erased event through hubsync.receive, and scrub.js being the same file in the sibling InstantAdPay checkout.
|
||||||
|
// node qa/erase.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } }
|
||||||
|
delete process.env.DATABASE_URL; delete process.env.DOCSTORE_URL;
|
||||||
|
const { scrubDeep, scrubText, mentions } = require(path.join(ROOT, 'scrub.js'));
|
||||||
|
const E = 'gone.person9@example.test', OTHER = 'stay@example.test';
|
||||||
|
const needles = { emails: [E], exact: ['goneuser', 'abc1234'] };
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('scrub: keys, list items, records and map values go; other people and look-alikes stay', () => {
|
||||||
|
const doc = { byEmail: { [E]: { u: 'goneuser' }, [OTHER]: { u: 'stay', sponsorEmail: 'x@example.test' } }, byCode: { abc1234: E, zzz9999: OTHER },
|
||||||
|
sends: [{ subject: 'Hi', recipients: [OTHER, E, 'xgone.person9@example.test'], delivered: [E] }],
|
||||||
|
log: [{ ts: 1, email: E, action: 'adopt' }, { ts: 2, email: OTHER }, { ts: 3, note: 'tankpay1:' + E + ':17' }],
|
||||||
|
clicks: { a1: { owner: E, n: 3 }, a2: { owner: OTHER, n: 1 } }, own: { 's:1': { [E]: 5, [OTHER]: 6 } }, nums: [1, 2, 3],
|
||||||
|
names: ['goneuserx', 'goneuser'], text: 'goneuser is a word here, kept',
|
||||||
|
prov: { [OTHER]: { sponsorEmail: E, at: 1 } }, team: [{ email: OTHER, sponsorEmail: E, ts: 4 }] };
|
||||||
|
const removed = scrubDeep(doc, needles);
|
||||||
|
assert.ok(removed >= 9, 'removed ' + removed);
|
||||||
|
assert.deepStrictEqual(Object.keys(doc.byEmail), [OTHER]); assert.deepStrictEqual(doc.byCode, { zzz9999: OTHER });
|
||||||
|
assert.deepStrictEqual(doc.sends[0].recipients, [OTHER, 'xgone.person9@example.test'], 'a longer address that contains it is someone else');
|
||||||
|
assert.deepStrictEqual(doc.sends[0].delivered, []); assert.deepStrictEqual(doc.log.map(x => x.ts), [2]);
|
||||||
|
assert.deepStrictEqual(Object.keys(doc.clicks), ['a2']); assert.deepStrictEqual(doc.own, { 's:1': { [OTHER]: 6 } });
|
||||||
|
assert.deepStrictEqual(doc.names, ['goneuserx'], 'a username only matches a whole string'); assert.strictEqual(doc.text, 'goneuser is a word here, kept');
|
||||||
|
assert.deepStrictEqual(doc.nums, [1, 2, 3]);
|
||||||
|
assert.deepStrictEqual(doc.prov, { [OTHER]: { sponsorEmail: null, at: 1 } }, "another member's record only loses the pointer");
|
||||||
|
assert.deepStrictEqual(doc.team, [{ email: OTHER, sponsorEmail: null, ts: 4 }]);
|
||||||
|
const lines = [JSON.stringify({ e: OTHER }), JSON.stringify({ e: E }), JSON.stringify({ u: 'goneuser' })].join('\n');
|
||||||
|
const r = scrubText(lines, needles, true); assert.strictEqual(r.removed, 2); assert.strictEqual(r.body, JSON.stringify({ e: OTHER }));
|
||||||
|
assert.strictEqual(mentions('{"a":"' + OTHER + '"}', needles), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- erase.js on a throwaway data dir ----
|
||||||
|
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-iap-'));
|
||||||
|
const W = (f, o) => fs.writeFileSync(path.join(DIR, f), typeof o === 'string' ? o : JSON.stringify(o));
|
||||||
|
const Rd = f => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8'));
|
||||||
|
W('updates-log.json', { sends: [{ subject: 'S', recipients: [OTHER, E], delivered: [E] }] });
|
||||||
|
W('legacy.json', { [E]: { b: 'faucetwave', s: 'e' }, [OTHER]: { b: 'tier1ads', s: 'a' } });
|
||||||
|
W('events.jsonl', JSON.stringify({ e: E }) + '\n' + JSON.stringify({ e: OTHER }));
|
||||||
|
W('unrelated.json', { a: OTHER });
|
||||||
|
// a module that keeps its document in memory and writes it back later (the reason erase works through the live copy)
|
||||||
|
let live = { rows: { [E]: { email: E, username: 'goneuser' }, [OTHER]: { email: OTHER } }, log: [{ email: E }] }; let saves = 0;
|
||||||
|
W('lsinbound.json', live);
|
||||||
|
const owner = { state: () => live, save: () => { saves++; W('lsinbound.json', live); } };
|
||||||
|
let reloads = 0;
|
||||||
|
const accts = { [E]: { email: E, username: 'goneuser', code: 'abc1234', address: null, memberId: 0 }, [OTHER]: { email: OTHER, username: 'stay', code: 'zzz9999', sponsorRef: '' },
|
||||||
|
'walleted@example.test': { email: 'walleted@example.test', username: 'wal', code: 'w1', address: '0x' + '1'.repeat(40), memberId: 0 } };
|
||||||
|
const accounts = { byEmail: async e => accts[e] || null, positions: async () => [], identities: async () => Object.values(accts),
|
||||||
|
listByReferrer: async refs => Object.values(accts).filter(a => refs.includes(a.sponsorRef)), removeAccount: async e => { if (!accts[e]) return { error: 'none' }; delete accts[e]; return { ok: true }; } };
|
||||||
|
accounts.listAll = async () => Object.values(accts);
|
||||||
|
let rot = [{ id: 7, owner: E }, { id: 8, owner: OTHER }]; const rotator = { eraseOwner: async (e, dry) => { const mine = rot.filter(r => r.owner === e); if (!dry) rot = rot.filter(r => r.owner !== e); return { rotations: mine.length, hits: 0, conv: 0 }; } };
|
||||||
|
const erase = require(path.join(ROOT, 'erase.js'));
|
||||||
|
let forgot = [];
|
||||||
|
erase.init({ dataDir: DIR, accounts, ads: { listCampaigns: async () => [] }, rotator, docstore: null, owners: { 'lsinbound.json': owner }, reload: { 'legacy.json': () => reloads++ }, forget: [e => forgot.push(e)] });
|
||||||
|
const before = fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8');
|
||||||
|
|
||||||
|
await t('dry run (the default) counts and changes nothing', async () => {
|
||||||
|
const r = await erase.erase(E);
|
||||||
|
assert.strictEqual(r.dryRun, true); assert.strictEqual(r.found, true); assert.deepStrictEqual(r.blockers, []);
|
||||||
|
assert.deepStrictEqual(Object.keys(r.docs).sort(), ['events.jsonl', 'legacy.json', 'lsinbound.json', 'updates-log.json']);
|
||||||
|
assert.strictEqual(fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8'), before); assert.ok(live.rows[E], 'live copy untouched');
|
||||||
|
assert.ok(accts[E]); assert.strictEqual(erase.isErased(E), false); assert.strictEqual(saves, 0); assert.strictEqual(r.spinLinks.rotations, 1); assert.strictEqual(rot.length, 2);
|
||||||
|
});
|
||||||
|
await t('a linked wallet blocks it, force overrides', async () => {
|
||||||
|
const r = await erase.erase('walleted@example.test', { dryRun: false }); assert.ok(/main wallet/.test(r.error)); assert.ok(accts['walleted@example.test']);
|
||||||
|
const f = await erase.erase('walleted@example.test', { dryRun: false, force: true }); assert.strictEqual(f.forced, true); assert.ok(!accts['walleted@example.test']);
|
||||||
|
});
|
||||||
|
await t('erase: the account, the live copy (saved), plain docs, JSON Lines; reload hook; caches; tombstone; others intact', async () => {
|
||||||
|
const r = await erase.erase(E, { dryRun: false });
|
||||||
|
assert.strictEqual(r.ok, true); assert.ok(!accts[E]); assert.ok(accts[OTHER]); assert.deepStrictEqual(rot, [{ id: 8, owner: OTHER }], 'their spin link went, not the other one');
|
||||||
|
assert.deepStrictEqual(Object.keys(live.rows), [OTHER]); assert.deepStrictEqual(live.log, []); assert.strictEqual(saves, 1);
|
||||||
|
assert.deepStrictEqual(Rd('lsinbound.json').rows[E], undefined);
|
||||||
|
assert.deepStrictEqual(Rd('updates-log.json').sends[0], { subject: 'S', recipients: [OTHER], delivered: [] });
|
||||||
|
assert.deepStrictEqual(Object.keys(Rd('legacy.json')), [OTHER]); assert.strictEqual(reloads, 1);
|
||||||
|
assert.strictEqual(fs.readFileSync(path.join(DIR, 'events.jsonl'), 'utf8'), JSON.stringify({ e: OTHER }));
|
||||||
|
assert.deepStrictEqual(r.docResidue, []); assert.deepStrictEqual(forgot.slice(-1), [E]);
|
||||||
|
assert.strictEqual(erase.isErased(E), true); assert.strictEqual(erase.isErased(OTHER), false);
|
||||||
|
const log = fs.readFileSync(path.join(DIR, 'erase.json'), 'utf8'); assert.ok(!log.includes(E), 'the erase log keeps no email'); assert.ok(log.includes(erase.hashOf(E).slice(0, 16)));
|
||||||
|
const again = await erase.erase(E, { dryRun: false }); assert.strictEqual(again.found, false); assert.deepStrictEqual(again.docs, {}, 'a second run finds nothing');
|
||||||
|
});
|
||||||
|
await t('hub member.erased: found by the email hash through hubsync.receive, answered 200', async () => {
|
||||||
|
accts['hubgone@example.test'] = { email: 'hubgone@example.test', username: 'hg', code: 'hg12345', address: null, memberId: 0 };
|
||||||
|
process.env.HUB_ENABLED = '1'; process.env.HUB_URL = 'http://127.0.0.1:9'; process.env.HUB_SECRET = 's'.repeat(40);
|
||||||
|
const hubsync = require(path.join(ROOT, 'hubsync.js'));
|
||||||
|
hubsync.init({ dataDir: DIR, accounts, registry: {}, carry: { hold() {}, unhold() {} }, follow: null, chain: null, erase, erased: e => erase.isErased(e) });
|
||||||
|
const raw = JSON.stringify({ events: [{ seq: 9001, at: Date.now(), type: 'member.erased', personId: 'h_' + '0'.repeat(16), data: { emailHash: erase.hashOf('HubGone@example.test') } }] });
|
||||||
|
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', 's'.repeat(40)).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw);
|
||||||
|
assert.strictEqual(r.status, 200); assert.ok(!accts['hubgone@example.test'], 'erased'); assert.strictEqual(erase.isErased('hubgone@example.test'), true);
|
||||||
|
const r2 = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw); assert.strictEqual(r2.status, 200, 'delivered twice is fine');
|
||||||
|
});
|
||||||
|
await t('scrub.js is the same file in the sibling checkout (InstantAdPay <-> LinkSpin)', () => {
|
||||||
|
const sib = [path.join(ROOT, '..', '..', 'linkspin', 'site'), path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site'), path.join(ROOT, '..', 'ls-erase'), path.join(ROOT, '..', 'iap-erase')]
|
||||||
|
.map(d => path.join(d, 'scrub.js')).find(f => fs.existsSync(f) && path.resolve(f) !== path.resolve(path.join(ROOT, 'scrub.js')));
|
||||||
|
if (!sib) { console.log(' (sibling scrub.js not found, skipped)'); return; }
|
||||||
|
const h = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||||
|
assert.strictEqual(h(path.join(ROOT, 'scrub.js')), h(sib), 'scrub.js differs from ' + sib);
|
||||||
|
});
|
||||||
|
console.log(fails ? fails + ' of ' + n + ' FAILED' : 'linkspin erase: all ' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// House Banner Spins admin route (2026-11-16). Boots server.js on its own port with a throwaway data dir (JSON store, no DB) and
|
||||||
|
// checks POST /api/admin/house-spins: admin only (no auth -> 401, logged as denied), house account only, creates a Banner Spin with
|
||||||
|
// its banners, source and fallback through the member code path, a second identical call changes nothing, an update adds / prunes
|
||||||
|
// by image, the image and click serve on a link domain (click -> the banner's target, src + s1 kept in the click row), every call
|
||||||
|
// is in the admin action log with who / what / when, and no member session is ever minted for the account.
|
||||||
|
// node qa/housespins.test.mjs (from the site dir; PORT default 8977)
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
|
||||||
|
const PORT = Number(process.env.PORT || 8977); const BASE = 'http://127.0.0.1:' + PORT;
|
||||||
|
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 500) : '')); } };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-qa-')); const ADMIN = 'admin@hs.test', MEM = 'mem@hs.test', KEY = 'k'.repeat(20), LINK = 'lnk-hs.test';
|
||||||
|
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: LINK }));
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: KEY, ADMIN_EMAIL: ADMIN });
|
||||||
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'DOCSTORE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL', 'NETWORK_LINKS_OWNER', 'NETWORK_SSO_SECRET']) delete env[k];
|
||||||
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
let srv = null;
|
||||||
|
async function boot() { srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] }); for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); } await sleep(3800); }
|
||||||
|
async function stop() { if (srv) srv.kill(); srv = null; await sleep(600); }
|
||||||
|
const read = f => { try { return JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8')); } catch (e) { return null; } };
|
||||||
|
const post = async (body, auth, actor) => { const r = await fetch(BASE + '/api/admin/house-spins', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, auth ? { Authorization: 'Bearer ' + auth } : {}, actor ? { 'X-Admin-Actor': actor } : {}), body: JSON.stringify(body) }); return { status: r.status, j: await r.json().catch(() => ({})) }; };
|
||||||
|
const go = async (p, ua) => { const r = await fetch(BASE + p, { redirect: 'manual', headers: { Host: LINK, 'User-Agent': ua || 'Mozilla/5.0 (Windows NT 10.0) Chrome/130 hs-qa', Referer: 'https://www.networkadspace.com/page' } }); return { status: r.status, loc: r.headers.get('location') || '', type: r.headers.get('content-type') || '' }; };
|
||||||
|
const sessionsFor = e => { const s = read('sessions.json'); const list = s ? (Array.isArray(s) ? s : Object.values(s.sessions || s)) : []; return list.filter(x => x && String(x.email || '').toLowerCase() === e).length; };
|
||||||
|
try {
|
||||||
|
await boot();
|
||||||
|
let src = null; for (let i = 0; i < 20 && !src; i++) { src = ((read('sources.json') || {}).items || []).find(x => x.owner === ADMIN && x.template === 'viraladblitz'); if (!src) await sleep(500); }
|
||||||
|
ok(!!src, 'the admin account has its network sources (one to tag with)');
|
||||||
|
const T = 'https://linkspin.app/r/nwvab?src=nas&s1=martbost';
|
||||||
|
const IMG = n => 'https://viraladblitz.com/art/kit/vab-' + n + '-panel.png';
|
||||||
|
const spin = (imgs, extra) => Object.assign({ name: 'Network Ad Space: ViralAdBlitz 336x280', size: '336x280', fallback: T, sourceId: src && src.id, banners: imgs.map(n => ({ label: n, image: IMG(n), target: T, weight: 10 })) }, extra || {});
|
||||||
|
const sess0 = sessionsFor(ADMIN);
|
||||||
|
|
||||||
|
let r = await post({ email: ADMIN, spins: [spin(['free'])] }, null, 'qa');
|
||||||
|
ok(r.status === 401, 'no admin auth: 401', r);
|
||||||
|
r = await post({ email: ADMIN, spins: [spin(['free'])] }, 'wrong-key');
|
||||||
|
ok(r.status === 401, 'a wrong admin key: 401', r);
|
||||||
|
r = await post({ email: MEM, spins: [spin(['free'])] }, KEY);
|
||||||
|
ok(r.status === 400 && /house account/.test(r.j.error || ''), 'a member account (not a house account): refused', r);
|
||||||
|
|
||||||
|
r = await post({ email: ADMIN, host: LINK, spins: [spin(['free', 'spread', 'boost'])] }, KEY, 'qa-run');
|
||||||
|
const s1 = r.j.spins && r.j.spins[0];
|
||||||
|
ok(r.status === 200 && r.j.ok && s1 && s1.created && s1.added === 3 && s1.sourceId === (src && src.id) && s1.fallback === T, 'creates the Banner Spin with 3 banners, the source and the fallback', r.j);
|
||||||
|
ok(s1 && s1.img === 'https://' + LINK + '/i/' + s1.code + '.gif' && s1.click === 'https://' + LINK + '/c/' + s1.code, 'answers the image and click URLs on the chosen link domain', s1);
|
||||||
|
const stored = (read('bannerspin.json') || { spins: [] }).spins.find(x => s1 && x.id === s1.id);
|
||||||
|
ok(stored && stored.owner === ADMIN && stored.banners.length === 3 && stored.banners.every(b => b.target === T && b.active), 'stored on the admin account like a member-made Banner Spin', stored);
|
||||||
|
|
||||||
|
r = await post({ email: ADMIN, host: LINK, spins: [spin(['free', 'spread', 'boost'])] }, KEY, 'qa-run');
|
||||||
|
ok(r.status === 200 && r.j.spins[0].id === s1.id && !r.j.spins[0].created && r.j.spins[0].added === 0 && r.j.spins[0].updated === 0, 'the same call again changes nothing (reuses it by name + size)', r.j.spins);
|
||||||
|
r = await post({ email: ADMIN, spins: [spin(['free', 'boost'], { id: s1.id, prune: true })] }, KEY, 'qa-run');
|
||||||
|
ok(r.status === 200 && r.j.spins[0].removed === 1 && r.j.spins[0].banners === 2, 'by id with prune: a banner no longer listed is removed', r.j.spins);
|
||||||
|
r = await post({ email: ADMIN, spins: [{ id: 99999, banners: [] }] }, KEY);
|
||||||
|
ok(r.status === 200 && r.j.ok === false && /No Banner Spin/.test(r.j.spins[0].errors[0] || ''), 'an unknown id reports an error and changes nothing', r.j);
|
||||||
|
r = await post({ email: ADMIN, spins: [spin(['free'], { name: 'Bad size', size: '999x999' })] }, KEY);
|
||||||
|
ok(r.status === 200 && r.j.ok === false && /sizes/.test(r.j.spins[0].errors[0] || ''), 'the member checks apply (a bad size is refused)', r.j);
|
||||||
|
|
||||||
|
let g = await go('/i/' + s1.code + '.gif');
|
||||||
|
ok(g.status === 302 && /^https:\/\/viraladblitz\.com\/art\/kit\/vab-(free|boost)-panel\.png$/.test(g.loc), 'the image URL serves one of the kit banners', g);
|
||||||
|
g = await go('/c/' + s1.code + '?src=nas&s1=martbost');
|
||||||
|
ok(g.status === 302 && g.loc.startsWith(T), 'the click goes to the tracked network link', g);
|
||||||
|
await sleep(300);
|
||||||
|
const click = (read('bannerspin.json') || { clicks: [] }).clicks.slice(-1)[0];
|
||||||
|
ok(click && click.s === s1.id && click.sr === src.id && click.q && click.q.src === 'nas' && click.q.s1 === 'martbost' && click.m !== 'none', 'the click row: this Banner Spin, the source, src + s1 kept, matched to the view', click);
|
||||||
|
|
||||||
|
const log = await (await fetch(BASE + '/api/admin/house-spins/log?limit=50', { headers: { Authorization: 'Bearer ' + KEY } })).json();
|
||||||
|
const E = log.entries || [];
|
||||||
|
ok(E.length === 8, 'every call is in the admin action log (8)', E.length);
|
||||||
|
ok(E.filter(e => !e.ok && /^denied/.test(e.who)).length === 2 && E.some(e => e.who === 'denied (qa)'), 'denied calls logged as denied, with the actor label', E.map(e => e.who));
|
||||||
|
ok(E.filter(e => e.who === 'admin key (qa-run)').length === 3 && E.every(e => e.action === 'house-spins' && e.ts > Date.now() - 600000), 'who (admin key + actor), what and when on each row', E.map(e => [e.who, e.action]));
|
||||||
|
ok(E.some(e => e.target === ADMIN && e.ok && e.detail && e.detail.spins && e.detail.spins[0].code === s1.code), 'the detail names the account and the Banner Spin', E[0]);
|
||||||
|
ok(!JSON.stringify(E).includes(KEY), 'the admin key is never in the log');
|
||||||
|
ok((await fetch(BASE + '/api/admin/house-spins/log')).status === 401, 'reading the log needs admin auth');
|
||||||
|
ok(sessionsFor(ADMIN) === sess0, 'no member session was minted for the account', [sess0, sessionsFor(ADMIN)]);
|
||||||
|
} catch (e) { fail++; console.error(e); }
|
||||||
|
finally { await stop(); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
||||||
|
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// The network ad writer client (2026-11-17): node qa/hubadwriter.test.mjs
|
||||||
|
// A stand-in hub checks the signature and answers like network-hub lib/adwriter.js; no real hub, no model, no member.
|
||||||
|
import http from 'node:http';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const ok = (c, m, extra) => { if (c) pass++; else { fail++; console.log('FAIL', m, extra !== undefined ? JSON.stringify(extra).slice(0, 300) : ''); } };
|
||||||
|
|
||||||
|
const SECRET = 's'.repeat(40); let seen = [], mode = 'good';
|
||||||
|
const hub = http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => {
|
||||||
|
const sig = crypto.createHmac('sha256', SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
|
||||||
|
r.setHeader('Content-Type', 'application/json');
|
||||||
|
if (sig !== q.headers['x-hub-sig']) { r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
|
||||||
|
const j = JSON.parse(b); seen.push({ path: q.url, site: q.headers['x-hub-site'], body: j });
|
||||||
|
if (q.url === '/v1/adwriter/status') return r.end(JSON.stringify(mode === 'off' ? { on: false, daily: 5 } : { on: true, daily: 5, left: j.member ? 3 : undefined }));
|
||||||
|
if (mode === 'limit') { r.statusCode = 429; return r.end(JSON.stringify({ ok: false, error: 'member_limit', code: 'member_limit', message: 'You have used your 5 ad writes for today.', left: 0 })); }
|
||||||
|
if (mode === 'slow') return;
|
||||||
|
r.end(JSON.stringify({ ok: true, options: [{ headline: 'One link for all your pages', line: 'Share one link that rotates your pages.' }], url: 'https://linkspin.app/', cached: false, left: 4 }));
|
||||||
|
}); });
|
||||||
|
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = SECRET; delete process.env.HUB_SITE; delete process.env.AI_WRITER;
|
||||||
|
const aw = require(path.join(ROOT, 'hubadwriter.js'));
|
||||||
|
|
||||||
|
ok(await aw.enabled(), 'on when the hub says on');
|
||||||
|
ok(seen[0].path === '/v1/adwriter/status' && seen[0].site && seen[0].site !== '__SITE__', 'signed as this site', seen[0]);
|
||||||
|
let r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||||
|
ok(r.ok && r.options.length === 1 && r.left === 4, 'options passed on', r);
|
||||||
|
ok(seen[1].body.member === 'member-1' && seen[1].body.limits.headline === 60 && seen[1].body.limits.line === 90 && seen[1].body.url === 'https://linkspin.app', 'member, url and this site\'s limits sent', seen[1].body);
|
||||||
|
mode = 'limit'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||||
|
ok(r.error === 'You have used your 5 ad writes for today.' && r.status === 429 && r.left === 0, 'the hub message is shown as is', r);
|
||||||
|
const st = await aw.status('member-1'); ok(st.on && st.left === 3, 'status for a member (left today)', st);
|
||||||
|
mode = 'off'; aw._reset(); ok(!(await aw.enabled()), 'off when the hub says off');
|
||||||
|
process.env.HUB_SECRET = 'w'.repeat(40); mode = 'good'; r = await aw.write('member-1', 'https://linkspin.app', { headline: 60, line: 90 });
|
||||||
|
ok(r.code === 'hub' && /busy/.test(r.error), 'a refused signature: a friendly busy message', r);
|
||||||
|
aw._reset(); ok(!(await aw.enabled()), 'a refused signature hides the button');
|
||||||
|
process.env.HUB_SECRET = SECRET; process.env.AI_WRITER = '0'; aw._reset(); const n0 = seen.length; ok(!(await aw.enabled()) && seen.length === n0, 'AI_WRITER=0 hides it without asking the hub', seen.length);
|
||||||
|
delete process.env.AI_WRITER; process.env.HUB_URL = 'http://127.0.0.1:1'; aw._reset(); ok(!(await aw.enabled()), 'an unreachable hub hides the button');
|
||||||
|
hub.close();
|
||||||
|
console.log('hubadwriter: ' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// The shared network knowledge base in this site's chatbot (2026-11-15): node qa/netkb-merge.test.cjs
|
||||||
|
// No network: netkb's merged set is set by hand. Checks: this site's entries rank first for a general question, a named site's
|
||||||
|
// entries rank first when it is named, other sites never take the fast path, the prompt labels them with the site and link,
|
||||||
|
// a question naming another site skips this site's instant answers (a hand-off still wins), and own() is this site only.
|
||||||
|
// The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||||
|
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'netkb-'));
|
||||||
|
delete process.env.DATABASE_URL; delete process.env.OPENROUTER_API_KEY; process.env.NETKB = '0';
|
||||||
|
const kb = require('../kb'); const netkb = require('../netkb'); const bot = require('../chatbot');
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
const ok = (c, m) => { if (c) { pass++; console.log('PASS', m); } else { fail++; console.log('FAIL', m); } };
|
||||||
|
(async () => {
|
||||||
|
await bot.init({ dataDir: DIR, chain: null });
|
||||||
|
const self = fs.existsSync(path.join(__dirname, '..', 'tickets.js')) ? 'iap' : 'linkspin';
|
||||||
|
netkb._set({ version: 'v1', sites: { downlinehydra: { name: 'DownlineHydra', url: 'https://downlinehydra.com' }, [self]: { name: 'Me', url: 'https://me.example' } },
|
||||||
|
entries: [
|
||||||
|
{ site: 'downlinehydra', id: 'c-pro', title: 'Pro: what it costs', questions: ['How much is Pro?', 'What do I get with Pro?'], answer: 'Pro is $30 one time.', tags: ['pro', 'price'] },
|
||||||
|
{ site: 'downlinehydra', id: 'c-withdraw', title: 'Withdrawals', questions: ['How do I withdraw?'], answer: 'Nothing to withdraw on DownlineHydra.', tags: ['withdraw'] },
|
||||||
|
{ site: self, id: 'c-own', title: 'Own entry from the hub', questions: ['x'], answer: 'never in remote', tags: [] }] });
|
||||||
|
await kb.load(true);
|
||||||
|
const top = async q => { const h = await kb.search(q, 8); return h[0] && h[0].entry; };
|
||||||
|
{ const t = await top('How do I withdraw?'); ok(t && !t.site, 'a general question ranks this site first (' + (t && t.id) + ')'); }
|
||||||
|
{ const t = await top('How do I withdraw on DownlineHydra?'); ok(t && t.site === 'downlinehydra', 'a named site ranks its own entry first (' + (t && t.id) + ')'); }
|
||||||
|
ok(!(await kb.search('Own entry from the hub', 8)).some(h => h.entry.site === self), 'this site\'s own copy on the hub is not read back as another site');
|
||||||
|
{ const b = kb.promptBlock(await kb.context('How much is Pro on DownlineHydra', 6)); ok(/about DownlineHydra, another network site; send people to /.test(b), 'remote entries labelled with site and link'); }
|
||||||
|
{ const r = await bot.answer('How much is Pro on DownlineHydra?'); ok(!r.canned, 'naming another site skips this site\'s instant answers (' + r.kb + ')'); }
|
||||||
|
{ const r = await bot.answer('How do I withdraw?'); ok(r.canned, 'this site\'s own question keeps its instant answer'); }
|
||||||
|
{ const r = await bot.answer('I need a real person, my DownlineHydra pro is missing'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
|
||||||
|
{ const own = await kb.own(); ok(own.length > 10 && own.every(e => !e.site), 'own(): this site\'s entries only (' + own.length + ')'); }
|
||||||
|
ok(kb.namesOther('what is 5xYourTeam', self).includes('fivex') && !kb.namesOther('what is this site', self).length, 'namesOther finds a network site by name');
|
||||||
|
for (const e of await kb.own()) ok(!/\bmetamask\b/i.test(e.answer.replace(/never recommend MetaMask/gi, '')), e.id + ': no MetaMask recommendation in a shared answer');
|
||||||
|
console.log((fail ? 'FAILED ' : 'all network KB checks passed: ') + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
|
})().catch(e => { console.error(e); process.exit(1); });
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// Semantic matching, site side (netkb.js route/suggest/match, 2026-11-16) + parity of the shared files: node qa/netkb-semantic.test.mjs
|
||||||
|
// A stand-in hub answers /v1/kb/match with scripted hits, so no model and no network. Checks: a sure match answers with this site's
|
||||||
|
// entry, a pattern hit is kept when the match agrees or has no idea and overruled when the match points elsewhere, other sites'
|
||||||
|
// entries rank behind this site's unless named or clearly closer, a named site that asks about "here" stays home, a slow or down hub
|
||||||
|
// answers null inside the timeout and is skipped for a while (fail soft), and the support suggestions never offer the contact-support entry.
|
||||||
|
// Parity: netkb.js is the same file in all eight network sites, chatcore.js + kb.js in the six that share them (checked against the
|
||||||
|
// sibling checkouts beside this one; a missing sibling is skipped, a different one fails).
|
||||||
|
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline Banners, Stack POL).
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
let pass = 0, fail = 0, skip = 0;
|
||||||
|
const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } };
|
||||||
|
|
||||||
|
// ---- parity with the sibling checkouts
|
||||||
|
const sha = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||||
|
const SIBLINGS = ['onchain-ad-membership/site', 'linkspin/site', 'vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol'];
|
||||||
|
const KIT = new Set(['vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol']);
|
||||||
|
let base = ROOT; for (let i = 0; i < 4 && !SIBLINGS.some(s => path.resolve(base, s) === ROOT); i++) base = path.dirname(base);
|
||||||
|
const mine = SIBLINGS.find(s => path.resolve(base, s) === ROOT);
|
||||||
|
for (const s of SIBLINGS) {
|
||||||
|
if (s === mine) continue;
|
||||||
|
const dir = path.resolve(base, s);
|
||||||
|
const files = ['netkb.js'].concat(mine && KIT.has(mine) && KIT.has(s) ? ['chatcore.js', 'kb.js'] : []);
|
||||||
|
for (const f of files) {
|
||||||
|
if (!fs.existsSync(path.join(dir, f))) { skip++; continue; }
|
||||||
|
ok(sha(path.join(dir, f)) === sha(path.join(ROOT, f)), 'parity: ' + f + ' differs from ' + s + '/' + f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ok(/The SAME file ships in every network site/.test(fs.readFileSync(path.join(ROOT, 'netkb.js'), 'utf8')), 'netkb.js carries the shared-file header');
|
||||||
|
|
||||||
|
// ---- a stand-in hub
|
||||||
|
let script = () => ({ hits: [], margin: 0 }), delay = 0, status = 200, last = null;
|
||||||
|
const hub = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||||
|
last = { path: req.url, body: JSON.parse(b || '{}'), site: req.headers['x-hub-site'] };
|
||||||
|
setTimeout(() => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(status === 200 ? Object.assign({ ok: true }, script(last.body)) : { error: 'embeddings_down' })); }, delay);
|
||||||
|
}); });
|
||||||
|
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = 'q'.repeat(40); process.env.HUB_SITE = 'home'; process.env.NETKB_MATCH_MS = '400';
|
||||||
|
delete process.env.NETKB; delete process.env.NETKB_MATCH;
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nksem-'));
|
||||||
|
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||||
|
netkb._set({ version: 'v', sites: { home: { name: 'Home', url: 'https://home.example' }, other: { name: 'Other', url: 'https://other.example' } },
|
||||||
|
entries: [{ site: 'other', id: 'c-split', title: 'Other split', questions: [], answer: 'Other split answer.', tags: [] }] });
|
||||||
|
const own = [{ id: 'c-split', title: 'Split', answer: 'Home split.' }, { id: 'c-packages', title: 'Packages', answer: 'Home prices.' }, { id: 'c-support', title: 'Support', answer: 'Ask support.', handoff: true }, { id: 'kb-t1', title: 'From a ticket', answer: 'Ticket answer.', source: 'ticket' }];
|
||||||
|
const H = (site, id, score) => ({ site, id, title: id, answer: '', score, boosted: score + (site === 'home' ? 0.08 : 0), home: site === 'home' });
|
||||||
|
const set = (hits, margin) => { script = () => ({ hits, margin: margin == null ? 0.1 : margin, confidence: hits.length ? hits[0].score : 0 }); };
|
||||||
|
|
||||||
|
// a sure match answers with this site's entry, even over a pattern hit that points elsewhere
|
||||||
|
set([H('home', 'c-split', 0.93), H('home', 'c-packages', 0.7)]);
|
||||||
|
let r = await netkb.route('how much do I earn', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'answer' && r.hit.id === 'c-split', 'sure match answers (' + JSON.stringify(r && [r.via, r.hit && r.hit.id]) + ')');
|
||||||
|
ok(last && last.path === '/v1/kb/match' && last.site === 'home' && last.body.k === 8, 'signed match call as this site');
|
||||||
|
// the pattern hit kept when the match agrees
|
||||||
|
set([H('home', 'c-split', 0.78), H('home', 'c-packages', 0.72)], 0.01);
|
||||||
|
r = await netkb.route('what does it cost', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'agree' && r.hit.id === 'c-packages', 'pattern kept when the match agrees (' + (r && r.via) + ')');
|
||||||
|
// the pattern hit kept when the match has no idea
|
||||||
|
set([H('home', 'c-split', 0.55)]);
|
||||||
|
r = await netkb.route('zzq', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'regex' && r.hit.id === 'c-packages', 'pattern kept when the match has no idea');
|
||||||
|
// overruled when the match points elsewhere with some confidence
|
||||||
|
set([H('home', 'c-split', 0.8), H('home', 'kb-t1', 0.75)], 0.05);
|
||||||
|
r = await netkb.route('what is my cut when my friends buy', { fast: own[1], own });
|
||||||
|
ok(r && r.via === 'veto' && r.hit === null && r.hits[0].entry.id === 'c-split', 'pattern overruled, the match feeds the prompt (' + (r && r.via) + ')');
|
||||||
|
// home first: another site's entry stays behind unless clearly closer
|
||||||
|
set([H('other', 'c-split', 0.82), H('home', 'c-split', 0.79)], 0.02);
|
||||||
|
r = await netkb.route('my cut', { own });
|
||||||
|
ok(r && r.via === 'context' && r.hits[0].entry.id === 'c-split' && !r.hits[0].entry.site, 'home entry first when no site is named');
|
||||||
|
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.70)], 0.2);
|
||||||
|
r = await netkb.route('other thing', { own });
|
||||||
|
ok(r && !r.hits[0].entry.site && r.hits.some(h => h.entry.site === 'other'), 'another site rides behind this site entry when clearly closer');
|
||||||
|
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.55)], 0.2);
|
||||||
|
r = await netkb.route('other thing', { own });
|
||||||
|
ok(r && r.hits[0].entry.site === 'other', 'another site leads when this site has nothing close');
|
||||||
|
// a named site asked about "here" stays home (no prefer sent)
|
||||||
|
set([H('home', 'c-split', 0.9)]);
|
||||||
|
await netkb.route('I am on Other, will my team carry over here?', { own, prefer: ['other'] });
|
||||||
|
ok(!last.body.prefer, 'named site + "here": no prefer');
|
||||||
|
await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||||
|
ok(Array.isArray(last.body.prefer) && last.body.prefer[0] === 'other', 'named site: prefer sent');
|
||||||
|
// remote never answers outright
|
||||||
|
set([H('other', 'c-split', 0.99)], 0.3);
|
||||||
|
r = await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||||
|
ok(r && r.hit === null && r.hits[0].entry.site === 'other', 'another site\'s entry rides as context, never the instant answer');
|
||||||
|
|
||||||
|
// suggestions: KB entries only, no contact-support entry, ticket-derived entries labelled
|
||||||
|
set([H('home', 'kb-t1', 0.82), H('home', 'c-support', 0.8), H('home', 'c-split', 0.79), H('home', 'c-packages', 0.5)]);
|
||||||
|
let s = await netkb.suggest('my payout never arrived after a purchase', { own });
|
||||||
|
ok(s.via === 'semantic' && s.items.map(i => i.id).join() === 'kb-t1,c-split', 'suggest: closest answers, no support entry, no weak ones (' + s.items.map(i => i.id) + ')');
|
||||||
|
ok(s.items[0].fromTicket === true && s.items[1].fromTicket === false, 'suggest: past-ticket entries labelled');
|
||||||
|
s = await netkb.suggest('hi', { own }); ok(s.items.length === 0 && s.via === 'short', 'suggest: too short asks nothing');
|
||||||
|
|
||||||
|
// fail soft: slow hub -> null inside the timeout, then skipped for a while; down hub -> null; suggest falls back to BM25
|
||||||
|
netkb._matchReset(); delay = 2000;
|
||||||
|
let t0 = Date.now(); r = await netkb.route('anything', { own }); const took = Date.now() - t0;
|
||||||
|
ok(r === null && took < 1500, 'slow hub: null within the timeout (' + took + ' ms)');
|
||||||
|
delay = 0; t0 = Date.now(); r = await netkb.route('anything', { own });
|
||||||
|
ok(r === null && Date.now() - t0 < 50, 'after a failure the hub is skipped for a while (no wait)');
|
||||||
|
s = await netkb.suggest('my payout never arrived after a purchase', { own, fallback: async () => [{ entry: own[0] }, { entry: own[2] }] });
|
||||||
|
ok(s.via === 'bm25' && s.items.map(i => i.id).join() === 'c-split', 'suggest falls back to BM25 when the hub is skipped');
|
||||||
|
netkb._matchReset(); status = 503;
|
||||||
|
r = await netkb.route('anything', { own }); ok(r === null, 'hub 503: null');
|
||||||
|
netkb._matchReset(); status = 200;
|
||||||
|
process.env.NETKB_MATCH = '0'; r = await netkb.route('anything', { own }); ok(r === null, 'NETKB_MATCH=0: off'); delete process.env.NETKB_MATCH;
|
||||||
|
const v = netkb.view(); ok(v.matchErrors >= 2 && v.semAnswer >= 1 && typeof v.sem.answer === 'number', 'view carries the semantic counters');
|
||||||
|
|
||||||
|
hub.close();
|
||||||
|
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed' + (skip ? ', ' + skip + ' sibling files not here (skipped)' : ''));
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
+72
-66
@@ -1,66 +1,72 @@
|
|||||||
// Network sites as traffic sources (2026-11-14). Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB)
|
// Network sites as traffic sources (2026-11-14). Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB)
|
||||||
// and checks: the admin account gets one fixed network link per site (nwiap, nwls, nwdlb, nwvbb, nwvab, nwsp, nwec) and one source per
|
// and checks: the admin account gets one fixed network link per site (nwiap, nwls, nwdlb, nwvbb, nwvab, nw5x, nwdh, nwsp, nwec) and one source per
|
||||||
// network site; /r/<code>?src=&s1=&s2= lands on the right page with ?ref=<member>; the click counts under the sending site's source;
|
// network site; /r/<code>?src=&s1=&s2= lands on the right page with ?ref=<member>; the click counts under the sending site's source;
|
||||||
// a member's own link with ?src=<site> gets that site's source made on first use; an unknown src changes nothing; a reboot makes
|
// a member's own link with ?src=<site> gets that site's source made on first use; an unknown src changes nothing; a reboot makes
|
||||||
// nothing twice.
|
// nothing twice.
|
||||||
// node qa/netsrc.test.mjs (from the site dir; PORT default 8973)
|
// node qa/netsrc.test.mjs (from the site dir; PORT default 8973)
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
|
|
||||||
const PORT = Number(process.env.PORT || 8973); const BASE = 'http://127.0.0.1:' + PORT;
|
const PORT = Number(process.env.PORT || 8973); const BASE = 'http://127.0.0.1:' + PORT;
|
||||||
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } };
|
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } };
|
||||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ns-qa-')); const now = Date.now(); const ADMIN = 'admin@ns.test', MEM = 'mem@ns.test';
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ns-qa-')); const now = Date.now(); const ADMIN = 'admin@ns.test', MEM = 'mem@ns.test';
|
||||||
fs.writeFileSync(path.join(DATA, 'sources.json'), JSON.stringify({ v: 1, items: [{ id: 'aaaaaaaaaa', owner: MEM, name: 'My mailer', template: 'custom', site: 'mailer.example', params: [], postbackUrl: '', events: ['join'], enabled: true, created: now }] }));
|
fs.writeFileSync(path.join(DATA, 'sources.json'), JSON.stringify({ v: 1, items: [{ id: 'aaaaaaaaaa', owner: MEM, name: 'My mailer', template: 'custom', site: 'mailer.example', params: [], postbackUrl: '', events: ['join'], enabled: true, created: now }] }));
|
||||||
fs.writeFileSync(path.join(DATA, 'rotator.json'), JSON.stringify({ v: 1, rotations: [
|
fs.writeFileSync(path.join(DATA, 'rotator.json'), JSON.stringify({ v: 1, rotations: [
|
||||||
{ id: 1, owner: MEM, name: 'Mine', code: 'memlnk', fallback: '', destinations: [{ id: 1, url: 'https://offer.example.org/', weight: 1, active: true }], created: now, paused: false, nextDest: 2, sourceId: 'aaaaaaaaaa' }], hits: [], conv: [] }));
|
{ id: 1, owner: MEM, name: 'Mine', code: 'memlnk', fallback: '', destinations: [{ id: 1, url: 'https://offer.example.org/', weight: 1, active: true }], created: now, paused: false, nextDest: 2, sourceId: 'aaaaaaaaaa' }], hits: [], conv: [] }));
|
||||||
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: ADMIN });
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: ADMIN });
|
||||||
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL', 'NETWORK_LINKS_OWNER', 'NETWORK_SSO_SECRET']) delete env[k];
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL', 'NETWORK_LINKS_OWNER', 'NETWORK_SSO_SECRET']) delete env[k];
|
||||||
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
let srv = null;
|
let srv = null;
|
||||||
async function boot() { srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] }); for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); } await sleep(3800); }
|
async function boot() { srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] }); for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); } await sleep(3800); }
|
||||||
async function stop() { if (srv) srv.kill(); srv = null; await sleep(600); }
|
async function stop() { if (srv) srv.kill(); srv = null; await sleep(600); }
|
||||||
const go = async (p, ref) => { const r = await fetch(BASE + p, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) Chrome/130 netsrc-qa' }, ref ? { Referer: ref } : {}) }); return { status: r.status, loc: r.headers.get('location') || '' }; };
|
const go = async (p, ref) => { const r = await fetch(BASE + p, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) Chrome/130 netsrc-qa' }, ref ? { Referer: ref } : {}) }); return { status: r.status, loc: r.headers.get('location') || '' }; };
|
||||||
const read = f => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));
|
const read = f => JSON.parse(fs.readFileSync(path.join(DATA, f), 'utf8'));
|
||||||
const srcOf = (owner, tpl) => read('sources.json').items.find(x => x.owner === owner && x.template === tpl);
|
const srcOf = (owner, tpl) => read('sources.json').items.find(x => x.owner === owner && x.template === tpl);
|
||||||
try {
|
try {
|
||||||
await boot();
|
await boot();
|
||||||
const rots = read('rotator.json').rotations.filter(r => r.owner === ADMIN);
|
const rots = read('rotator.json').rotations.filter(r => r.owner === ADMIN);
|
||||||
ok(['nwiap', 'nwls', 'nwdlb', 'nwvbb', 'nwvab', 'nwsp', 'nwec'].every(c => rots.some(r => r.code === c)) && rots.length === 7, 'the admin account has the seven network links', rots.map(r => r.code));
|
ok(['nwiap', 'nwls', 'nwdlb', 'nwvbb', 'nwvab', 'nwvas', 'nwypb', 'nwvai', 'nwst', 'nw5x', 'nwdh', 'nwsp', 'nwec'].every(c => rots.some(r => r.code === c)) && rots.length === 13, 'the admin account has the thirteen network links', rots.map(r => r.code));
|
||||||
const mineSrc = read('sources.json').items.filter(x => x.owner === ADMIN);
|
const mineSrc = read('sources.json').items.filter(x => x.owner === ADMIN);
|
||||||
ok(['instantadpay', 'linkspin', 'downlinebanners', 'viralbannerblitz', 'viraladblitz', 'stackpol', 'earnerscorner'].every(t => mineSrc.some(x => x.template === t)) && mineSrc.length === 7, 'and one source per network site', mineSrc.map(x => x.template));
|
ok(['instantadpay', 'linkspin', 'downlinebanners', 'viralbannerblitz', 'viraladblitz', 'viraladsource', 'yourprogrambuilder', 'videoappincome', 'socialtube', '5xyourteam', 'downlinehydra', 'stackpol', 'earnerscorner'].every(t => mineSrc.some(x => x.template === t)) && mineSrc.length === 13, 'and one source per network site', mineSrc.map(x => x.template));
|
||||||
|
|
||||||
let r = await go('/r/nwdlb?src=iap&s1=bob&s2=how');
|
let r = await go('/r/nwdlb?src=iap&s1=bob&s2=how');
|
||||||
ok(r.status === 302 && /^https:\/\/downlinebanners\.com\/how\?ref=bob$/.test(r.loc), 'nwdlb: lands on /how with ?ref=bob', r);
|
ok(r.status === 302 && /^https:\/\/downlinebanners\.com\/how\?ref=bob$/.test(r.loc), 'nwdlb: lands on /how with ?ref=bob', r);
|
||||||
r = await go('/r/nwiap?src=vbb&s1=amy');
|
r = await go('/r/nwiap?src=vbb&s1=amy');
|
||||||
ok(r.status === 302 && /^https:\/\/instantadpay\.com\/\?ref=amy&lsclk=[a-f0-9]{10}$/.test(r.loc), 'nwiap: home page with ?ref=amy and the click id (InstantAdPay reports joins against it)', r);
|
ok(r.status === 302 && /^https:\/\/instantadpay\.com\/\?ref=amy&lsclk=[a-f0-9]{10}$/.test(r.loc), 'nwiap: home page with ?ref=amy and the click id (InstantAdPay reports joins against it)', r);
|
||||||
r = await go('/r/nwec?src=dlb');
|
r = await go('/r/nwvai?src=iap&s1=amy&s2=join');
|
||||||
ok(r.status === 302 && /^https:\/\/earnerscorner\.com\/(\?|$)/.test(r.loc), 'nwec: the forum home', r);
|
ok(r.status === 302 && /^https:\/\/videoappincome\.com\/join\?ref=amy&lsclk=[a-f0-9]{10}$/.test(r.loc), 'nwvai: Video App Income join page with ?ref=amy and the click id (it reports sign-ups and purchases against it)', r);
|
||||||
r = await go('/r/nwvab?src=vab&s1=bob&s2=boost');
|
r = await go('/r/nwec?src=dlb');
|
||||||
ok(r.status === 302 && /^https:\/\/viraladblitz\.com\/boost\?ref=bob$/.test(r.loc), 'nwvab: ViralAdBlitz page with the member ref', r);
|
ok(r.status === 302 && /^https:\/\/earnerscorner\.com\/(\?|$)/.test(r.loc), 'nwec: the forum home', r);
|
||||||
r = await go('/r/nwvbb?src=linkspin', 'https://linkspin.app/contract');
|
r = await go('/r/nwdh?src=downlinehydra&s1=bob');
|
||||||
ok(r.status === 302 && /^https:\/\/viralbannerblitz\.com\/\?ref=(&|$)/.test(r.loc), 'nwvbb with no member: an empty ref', r);
|
ok(r.status === 302 && /^https:\/\/downlinehydra\.com\/\?ref=bob$/.test(r.loc), 'nwdh: DownlineHydra with the member ref', r);
|
||||||
await sleep(300);
|
r = await go('/r/nw5x?src=fivex&s1=bob');
|
||||||
const hits = read('rotator.json').hits; const byCode = c => { const rr = read('rotator.json').rotations.find(x => x.code === c); return hits.filter(h => h.r === rr.id); };
|
ok(r.status === 302 && /^https:\/\/5xyourteam\.com\/\?ref=bob$/.test(r.loc), 'nw5x: 5xYourTeam with the member ref', r);
|
||||||
const h1 = byCode('nwdlb')[0], h2 = byCode('nwiap')[0], h3 = byCode('nwec')[0], h4 = byCode('nwvbb')[0];
|
r = await go('/r/nwvab?src=vab&s1=bob&s2=boost');
|
||||||
ok(h1 && h1.sr === srcOf(ADMIN, 'instantadpay').id && h1.s === 'instantadpay.com' && h1.q.s1 === 'bob', 'the DLB click counts under the InstantAdPay source (no referrer: the site name)', h1);
|
ok(r.status === 302 && /^https:\/\/viraladblitz\.com\/boost\?ref=bob$/.test(r.loc), 'nwvab: ViralAdBlitz page with the member ref', r);
|
||||||
ok(h2 && h2.sr === srcOf(ADMIN, 'viralbannerblitz').id, 'the IAP click counts under the Viral Banner Blitz source', h2);
|
r = await go('/r/nwvbb?src=linkspin', 'https://linkspin.app/contract');
|
||||||
ok(h3 && h3.sr === srcOf(ADMIN, 'downlinebanners').id, 'the Earners Corner click counts under the Downline Banners source', h3);
|
ok(r.status === 302 && /^https:\/\/viralbannerblitz\.com\/\?ref=(&|$)/.test(r.loc), 'nwvbb with no member: an empty ref', r);
|
||||||
ok(h4 && h4.sr === srcOf(ADMIN, 'linkspin').id && h4.s === 'linkspin.app', 'a real referrer is kept as the referrer', h4);
|
await sleep(300);
|
||||||
|
const hits = read('rotator.json').hits; const byCode = c => { const rr = read('rotator.json').rotations.find(x => x.code === c); return hits.filter(h => h.r === rr.id); };
|
||||||
ok(!srcOf(MEM, 'stackpol'), 'the member has no Stack POL source yet');
|
const h1 = byCode('nwdlb')[0], h2 = byCode('nwiap')[0], h3 = byCode('nwec')[0], h4 = byCode('nwvbb')[0];
|
||||||
r = await go('/r/memlnk?src=stackpol');
|
ok(h1 && h1.sr === srcOf(ADMIN, 'instantadpay').id && h1.s === 'instantadpay.com' && h1.q.s1 === 'bob', 'the DLB click counts under the InstantAdPay source (no referrer: the site name)', h1);
|
||||||
ok(r.status === 302 && /^https:\/\/offer\.example\.org\//.test(r.loc), 'a member link with ?src=stackpol still redirects', r);
|
ok(h2 && h2.sr === srcOf(ADMIN, 'viralbannerblitz').id, 'the IAP click counts under the Viral Banner Blitz source', h2);
|
||||||
await go('/r/memlnk?src=nosuchsite'); await go('/r/memlnk'); await sleep(300);
|
ok(h3 && h3.sr === srcOf(ADMIN, 'downlinebanners').id, 'the Earners Corner click counts under the Downline Banners source', h3);
|
||||||
const ms = srcOf(MEM, 'stackpol'); const mh = read('rotator.json').hits.filter(h => h.r === 1);
|
ok(h4 && h4.sr === srcOf(ADMIN, 'linkspin').id && h4.s === 'linkspin.app', 'a real referrer is kept as the referrer', h4);
|
||||||
ok(ms && ms.name === 'Stack POL', 'the member got a Stack POL source on first use', ms);
|
|
||||||
ok(mh.length === 3 && mh[0].sr === ms.id && mh[1].sr === 'aaaaaaaaaa' && mh[2].sr === 'aaaaaaaaaa', 'that click counts under it; an unknown src or none keeps the attached source', mh.map(h => h.sr));
|
ok(!srcOf(MEM, 'stackpol'), 'the member has no Stack POL source yet');
|
||||||
ok(read('sources.json').items.filter(x => x.owner === MEM).length === 2, 'an unknown src makes no source');
|
r = await go('/r/memlnk?src=stackpol');
|
||||||
|
ok(r.status === 302 && /^https:\/\/offer\.example\.org\//.test(r.loc), 'a member link with ?src=stackpol still redirects', r);
|
||||||
await stop(); await boot();
|
await go('/r/memlnk?src=nosuchsite'); await go('/r/memlnk'); await sleep(300);
|
||||||
ok(read('rotator.json').rotations.filter(x => x.owner === ADMIN).length === 7 && read('sources.json').items.filter(x => x.owner === ADMIN).length === 7, 'a reboot makes nothing twice');
|
const ms = srcOf(MEM, 'stackpol'); const mh = read('rotator.json').hits.filter(h => h.r === 1);
|
||||||
} catch (e) { fail++; console.error(e); }
|
ok(ms && ms.name === 'Stack POL', 'the member got a Stack POL source on first use', ms);
|
||||||
finally { await stop(); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
ok(mh.length === 3 && mh[0].sr === ms.id && mh[1].sr === 'aaaaaaaaaa' && mh[2].sr === 'aaaaaaaaaa', 'that click counts under it; an unknown src or none keeps the attached source', mh.map(h => h.sr));
|
||||||
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
ok(read('sources.json').items.filter(x => x.owner === MEM).length === 2, 'an unknown src makes no source');
|
||||||
|
|
||||||
|
await stop(); await boot();
|
||||||
|
ok(read('rotator.json').rotations.filter(x => x.owner === ADMIN).length === 13 && read('sources.json').items.filter(x => x.owner === ADMIN).length === 13, 'a reboot makes nothing twice');
|
||||||
|
} catch (e) { fail++; console.error(e); }
|
||||||
|
finally { await stop(); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
||||||
|
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// LinkSpin -> network hub activity (Marty 2026-11-16: "LinkSpin never reports activity", DownlineHydra "Wake it").
|
||||||
|
// node qa/networksso-activity.test.mjs (needs ../../network-hub beside this repo; skips otherwise)
|
||||||
|
// Boots the REAL hub (JSON store, throwaway dir) and drives networksso.js in this process the way server.js does:
|
||||||
|
// 1. a signed-in member's real page load (/links, Sec-Fetch-Dest: document) records site 'linkspin' on the hub
|
||||||
|
// 2. a second page load the same day sends nothing more (once a day)
|
||||||
|
// 3. API calls, assets, bots and signed-out page loads never ping
|
||||||
|
// 4. seen() (what /api/me, /api/my/ping and the admin portal call): a tab kept open, a browser with no Sec-Fetch headers,
|
||||||
|
// and a wallet-only session all record the day's visit
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'activity.js')));
|
||||||
|
if (!HUB_DIR) { console.log('SKIP activity test: needs ../../network-hub'); process.exit(0); }
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
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 KEY = crypto.randomBytes(24).toString('hex'); const HP = Number(process.env.ACT_HUB_PORT || 8871); const HUB = 'http://127.0.0.1:' + HP;
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-act-'));
|
||||||
|
let hubLog = '';
|
||||||
|
const hub = spawn(process.execPath, ['server.js'], { cwd: HUB_DIR, stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: Object.assign({}, process.env, { PORT: String(HP), DATA_DIR: TMP, DATABASE_URL: '', HUB_ADMIN_SECRET: '', HUB_FORUM_URL: '', HUB_FORUM_API_KEY: '', HUB_SITES: JSON.stringify({ linkspin: { secret: KEY } }) }) });
|
||||||
|
hub.stdout.on('data', d => hubLog += d); hub.stderr.on('data', d => hubLog += d);
|
||||||
|
const done = code => { try { hub.kill(); } catch (e) {} try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {} process.exit(code); };
|
||||||
|
|
||||||
|
async function call(route, body) {
|
||||||
|
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||||
|
const r = await fetch(HUB + route, { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': 'linkspin', 'X-Hub-Ts': ts, 'X-Hub-Sig': crypto.createHmac('sha256', KEY).update(ts + '\n' + raw).digest('hex') } });
|
||||||
|
return { status: r.status, body: await r.json().catch(() => null) };
|
||||||
|
}
|
||||||
|
const lsAt = async id => { const r = await call('/v1/activity/person', { id }); return r.body && r.body.sites && r.body.sites.linkspin ? r.body.sites.linkspin : null; };
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 40; i++) { try { if ((await fetch(HUB + '/health')).ok) break; } catch (e) {} await sleep(250); }
|
||||||
|
// members on the hub (joined from LinkSpin), one with a wallet
|
||||||
|
const a = (await call('/v1/join', { email: 'ann@example.com', username: 'annls' })).body.person;
|
||||||
|
const b = (await call('/v1/join', { email: 'ben@example.com', username: 'benls' })).body.person;
|
||||||
|
const c = (await call('/v1/join', { email: 'cat@example.com', username: 'catls' })).body.person;
|
||||||
|
const W = '0x' + '7'.repeat(40);
|
||||||
|
const wr = await call('/v1/wallet', { email: 'cat@example.com', wallet: W });
|
||||||
|
ok(a && a.id && b && b.id && c && c.id && wr.status === 200, 'the hub is up with three LinkSpin members (one with a wallet)', JSON.stringify(wr.body).slice(0, 160));
|
||||||
|
|
||||||
|
process.env.HUB_URL = HUB; process.env.HUB_SECRET = KEY; process.env.HUB_SITE = 'linkspin'; process.env.HUB_SSO = ''; process.env.HUB_ACTIVITY = '';
|
||||||
|
const nsso = require(path.join(HERE, 'networksso.js'));
|
||||||
|
const sessions = { 'tok-ann': { email: 'ann@example.com' }, 'tok-ben': { email: 'ben@example.com' } };
|
||||||
|
nsso.init({ self: 'linkspin', peer: 'iap', peerBase: () => 'http://127.0.0.1:1', isProd: false, dataDir: TMP, db: null, defaultPath: '/ads',
|
||||||
|
member: async req => { const m = /sid=([^;]+)/.exec(req.headers.cookie || ''); return m ? sessions[m[1]] || null : null; } });
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
const req = (url, sid, h) => ({ method: 'GET', url, headers: Object.assign({ 'user-agent': UA, 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate' }, sid ? { cookie: 'sid=' + sid } : {}, h || {}) });
|
||||||
|
const res = () => ({ writeHead() { this.redirected = true; }, end() {} });
|
||||||
|
const load = async (url, sid, h) => { const r = res(); const answered = await nsso.page(req(url, sid, h), r, new URL(url, 'http://x')); return answered || !!r.redirected; };
|
||||||
|
|
||||||
|
// 1. a signed-in page load records 'linkspin'
|
||||||
|
ok((await lsAt(a.id)) === null, 'before: ann has no LinkSpin activity on the hub');
|
||||||
|
ok((await load('/links', 'tok-ann')) === false, 'the page load is served normally (no redirect with the hub sign-in off)');
|
||||||
|
await sleep(500);
|
||||||
|
const r1 = await lsAt(a.id);
|
||||||
|
ok(r1 && r1.lastKind === 'visit' && Date.now() - r1.lastAt < 10000, 'a signed-in LinkSpin page load records site linkspin on the hub', JSON.stringify(r1));
|
||||||
|
// 2. once a day
|
||||||
|
ok(nsso._pinged.has('ann@example.com'), 'ann is marked pinged for today');
|
||||||
|
await load('/ads', 'tok-ann'); await sleep(300);
|
||||||
|
ok((await lsAt(a.id)).lastAt === r1.lastAt, 'a second page load the same day sends nothing more');
|
||||||
|
// 3. never for API calls, assets, bots or signed-out loads
|
||||||
|
await load('/api/me', 'tok-ben'); await load('/assets/site.css', 'tok-ben'); await load('/links', 'tok-ben', { 'user-agent': 'curl/8.0' });
|
||||||
|
await load('/links', 'tok-ben', { 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors' }); await load('/links', null); await sleep(400);
|
||||||
|
ok((await lsAt(b.id)) === null && !nsso._pinged.has('ben@example.com'), 'API calls, assets, bots, fetches and signed-out loads never ping');
|
||||||
|
// 4. seen(): /api/me and the heartbeat (no Sec-Fetch headers needed), the admin portal, a wallet-only session
|
||||||
|
ok(nsso.seen({ email: 'Ben@Example.com' }) === true, 'seen() (the /api/me and /api/my/ping hook) takes a signed-in session');
|
||||||
|
ok(nsso.seen({ address: W }) === true && nsso.seen(null) === false && nsso.seen({}) === false, 'seen(): a wallet-only session pings by wallet; nobody signed in pings nothing');
|
||||||
|
await sleep(600);
|
||||||
|
const rb = await lsAt(b.id), rc = await lsAt(c.id);
|
||||||
|
ok(rb && rb.lastKind === 'visit', 'a Control Room tab kept open (no page load) still records the day on the hub', JSON.stringify(rb));
|
||||||
|
ok(rc && rc.lastKind === 'visit', 'a wallet-only session records the day for the person who owns the wallet', JSON.stringify(rc));
|
||||||
|
const n = nsso._pinged.size; nsso.seen({ email: 'ben@example.com' }); ok(nsso._pinged.size === n, 'seen() keeps the once-a-day rule');
|
||||||
|
const srv = fs.readFileSync(path.join(HERE, 'server.js'), 'utf8');
|
||||||
|
ok(/networksso\.seen\(\{ email: s\.email \|\| \(acct && acct\.email\)/.test(srv) && /touchSeen\(s\.email\)\.catch\(\(\) => \{\}\); networksso\.seen\(s\)/.test(srv) && /adminFromRequest\(req\); if \(adm && adm\.email\) networksso\.seen/.test(srv), 'server.js calls seen() from /api/me, the dashboard heartbeat and the admin portal');
|
||||||
|
} catch (e) { ok(false, 'test crashed', String(e && e.stack || e).slice(0, 400)); }
|
||||||
|
if (fails) console.log('hub log:\n' + hubLog.slice(-1500));
|
||||||
|
console.log(fails ? fails + ' failed' : 'all passed');
|
||||||
|
done(fails ? 1 : 0);
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
// The network hub as the sign-in provider (Marty 2026-11-15), end to end. Same file in InstantAdPay and LinkSpin.
|
||||||
|
// node qa/networksso-hub.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
|
||||||
|
// Boots the real hub (JSON store), InstantAdPay, LinkSpin and a stand-in wallet partner (the 5xYourTeam shape) with HUB_SSO=on,
|
||||||
|
// each on its own cookie host (hub 127.0.0.3, IAP 127.0.0.1, LinkSpin localhost, partner 127.0.0.2), and drives a real browser:
|
||||||
|
// 1. a code sign-in on IAP, then any IAP page: the page load goes once through the hub (/sso/set) and the hub sign-in is set
|
||||||
|
// 2. same browser, a LinkSpin screen: the silent check asks the HUB (not IAP) and signs in with no code
|
||||||
|
// 3. same browser, the partner's "Sign in with InstantAdPay": the hub answers with a token carrying the wallet
|
||||||
|
// 4. Sign out everywhere on LinkSpin: the hub sign-in ends, a fresh partner check gets "nobody" from the hub
|
||||||
|
// 5. a blocked member: the hub refuses; a replayed hub token is refused; no email-code request by any network sign-in
|
||||||
|
// The partner takes the hub's hook with the real wallet-site hubevents.js (from ../../5xyourteam/app, 2026-11-16): its session
|
||||||
|
// open on the partner ends after Sign out everywhere (step 4) and after a hub block (step 5).
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||||
|
const PEER = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'sso.js')));
|
||||||
|
if (!PEER || !HUB_DIR) { console.log('SKIP hub sign-in e2e: needs the other site and network-hub (with lib/sso.js) beside this repo.'); process.exit(0); }
|
||||||
|
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WALLET_DIR = [process.env.WALLET_SITE_DIR, path.resolve(HERE, '../../5xyourteam/app')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'hubevents.js')));
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||||
|
const SSO = crypto.randomBytes(24).toString('hex');
|
||||||
|
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), fivex: crypto.randomBytes(24).toString('hex') };
|
||||||
|
const ADMIN = crypto.randomBytes(24).toString('hex');
|
||||||
|
const IP = Number(process.env.NSSO_IAP_PORT || 8841), LP = IP + 1, PP = IP + 2, HP = IP + 3;
|
||||||
|
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP, HUB = 'http://127.0.0.3:' + HP;
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
const fetch0 = globalThis.fetch;
|
||||||
|
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-hub-'));
|
||||||
|
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||||
|
fs.writeFileSync(SPY, "const http=require('http');const e=http.Server.prototype.emit;http.Server.prototype.emit=function(ev,req){if(ev==='request'&&req&&req.url)process.stdout.write('REQ '+req.method+' '+String(req.url).split('?')[0]+'\\n');return e.apply(this,arguments);};\n");
|
||||||
|
const logs = { iap: '', ls: '', hub: '' };
|
||||||
|
function boot(name, dir, port, script, extra) {
|
||||||
|
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||||
|
NETWORK_SSO_SECRET: SSO, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P, HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0',
|
||||||
|
NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, extra);
|
||||||
|
const p = spawn(process.execPath, [script], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||||
|
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||||
|
}
|
||||||
|
const srvH = boot('hub', HUB_DIR, HP, 'server.js', { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: ADMIN, HUB_HOOK_EVERY_MS: '1000',
|
||||||
|
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, fivex: Object.assign({ secret: K.fivex }, WALLET_DIR ? { hook: P + '/api/hub/events' } : {}) }),
|
||||||
|
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, fivex: P }) });
|
||||||
|
const srvI = boot('iap', IAP_DIR, IP, 'server.js', { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
|
||||||
|
const srvL = boot('ls', LS_DIR, LP, 'server.js', { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
|
||||||
|
|
||||||
|
// the stand-in wallet partner (self fivex), hub mode on, in this process
|
||||||
|
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K.fivex, HUB_SITE: 'fivex', HUB_SSO: 'on', HUB_ACTIVITY: '0' });
|
||||||
|
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||||
|
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||||
|
const partnerLog = []; const origLog = console.log; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
|
||||||
|
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/team',
|
||||||
|
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||||
|
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||||
|
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss, at: Date.now() }); return 'fx.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||||
|
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||||
|
// the hub's hook into the partner: the real wallet-site module, ending partner sessions made before the event
|
||||||
|
const HE = WALLET_DIR ? require(path.join(WALLET_DIR, 'hubevents.js')) : null;
|
||||||
|
if (HE) HE.init({ dataDir: TMP, site: 'fivex', end: who => { let n = 0; for (const [k, x] of PS) if (x.at <= who.before && who.match(x)) { PS.delete(k); n++; } return n; } });
|
||||||
|
const partner = http.createServer(async (req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x');
|
||||||
|
if (HE && u.pathname === '/api/hub/events' && req.method === 'POST') { let raw = ''; for await (const c of req) raw += c; const r = await HE.receive(req.headers, raw); res.writeHead(r.status, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(r.body)); }
|
||||||
|
if (req.method === 'GET' && await N.page(req, res, u)) return;
|
||||||
|
if (await N.handle(req, res, u)) return;
|
||||||
|
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p>' + u.pathname + '</p>');
|
||||||
|
});
|
||||||
|
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||||
|
|
||||||
|
const signHub = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||||
|
async function hubCall(route, site, secret, body) { const raw = JSON.stringify(body); const ts = String(Date.now()); const r = await fetch(HUB + route, { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Hub-Site': site, 'X-Hub-Ts': ts, 'X-Hub-Sig': signHub(secret, ts, raw) } }); return { status: r.status, json: await r.json().catch(() => ({})) }; }
|
||||||
|
let ipN = 50;
|
||||||
|
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.7.0.' + (ipN++), 'User-Agent': UA });
|
||||||
|
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||||
|
async function codeSignIn(base, email) {
|
||||||
|
const h = H();
|
||||||
|
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||||
|
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||||
|
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||||
|
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base);
|
||||||
|
const un = 'h' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 12) + crypto.randomBytes(2).toString('hex');
|
||||||
|
await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||||
|
return sid;
|
||||||
|
}
|
||||||
|
const meOf = async (ctx, base) => { const r = await ctx.request.get(base + '/api/me', { headers: { Accept: 'application/json' } }); try { return await r.json(); } catch (e) { return {}; } };
|
||||||
|
const codeReqs = () => (logs.iap + logs.ls).split('\n').filter(l => /^REQ POST \/api\/auth\/email\/(start|verify)$/.test(l)).length;
|
||||||
|
let browser = null;
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 240; i++) { let a = false, b = false, c = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} try { c = (await fetch(HUB + '/health')).ok; } catch (e) {} if (a && b && c) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b + ', hub ' + c); await sleep(500); }
|
||||||
|
await sleep(1500); // each site's first hub /health answer
|
||||||
|
N._hubSeen();
|
||||||
|
browser = await chromium.launch();
|
||||||
|
const A = 'hub-a@example.com', wA = ethers.Wallet.createRandom().address.toLowerCase();
|
||||||
|
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
|
||||||
|
// the hub knows A (in production the sites' hubsync sends joins; here the test joins A as InstantAdPay) with a wallet
|
||||||
|
ok((await hubCall('/v1/join', 'iap', K.iap, { email: A, username: 'huba' })).status === 200 && (await hubCall('/v1/wallet', 'iap', K.iap, { email: A, wallet: wA })).status === 200, 'setup: A on the hub with a wallet');
|
||||||
|
const codes0 = codeReqs();
|
||||||
|
|
||||||
|
// 1. an IAP page load tells the hub
|
||||||
|
const ctx = await browser.newContext({ userAgent: UA }); await ctx.addCookies([{ name: 'iap.sid', value: aI, domain: '127.0.0.1', path: '/' }]);
|
||||||
|
const page = await ctx.newPage(); const navs = []; page.on('request', r => { if (r.isNavigationRequest() && r.frame() === page.mainFrame()) navs.push(r.url()); }); // every hop, 302s included
|
||||||
|
await page.goto(IAP + '/my#overview'); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(1000);
|
||||||
|
ok(navs.some(u => u.startsWith(HUB + '/sso/set?site=iap')) && page.url().startsWith(IAP + '/my'), '1. IAP page load went once through the hub and came back', navs.map(u => u.slice(0, 45)).join(' , '));
|
||||||
|
ok((await ctx.cookies(HUB)).some(c => c.name === 'hub.sso' && c.httpOnly && c.sameSite === 'Lax'), '1. the hub sign-in cookie is set (HttpOnly, SameSite=Lax) on the hub host');
|
||||||
|
const before = navs.length; await page.goto(IAP + '/my'); await page.waitForTimeout(800);
|
||||||
|
ok(!navs.slice(before).some(u => u.startsWith(HUB)), '1. the next page load does not go through the hub again');
|
||||||
|
|
||||||
|
// 2. LinkSpin signs in through the hub, no code
|
||||||
|
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 20000 }); await page.waitForTimeout(2500);
|
||||||
|
ok((await meOf(ctx, LS)).email === A, '2. LinkSpin screen opened directly: signed in through the hub', page.url());
|
||||||
|
ok(navs.some(u => u.startsWith(HUB + '/sso/check?site=linkspin')) && /signed in from the network hub/.test(logs.ls), '2. it asked the hub, not InstantAdPay');
|
||||||
|
|
||||||
|
// 3. the partner: Sign in with InstantAdPay -> the hub answers, with the wallet
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?x=1')); await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||||
|
const who = await (await ctx.request.get(P + '/api/whoami')).json();
|
||||||
|
ok(page.url() === P + '/team?x=1' && who.address === wA && who.via === 'hub', '3. partner signed in by the hub with the member\'s wallet', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
|
||||||
|
// 4. Sign out everywhere on LinkSpin
|
||||||
|
const out = await (await ctx.request.post(LS + '/api/auth/logout-everywhere')).json();
|
||||||
|
ok(out.ok && out.everywhere === true && !(await meOf(ctx, LS)).signedIn, '4. Sign out everywhere: signed out on LinkSpin, the hub confirmed', JSON.stringify(out));
|
||||||
|
const hubNow = await ctx.request.get(HUB + '/sso/check?site=fivex&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
|
||||||
|
ok(/none=1&hub=1/.test(hubNow.headers()['location'] || ''), '4. the hub sign-in is gone', hubNow.headers()['location']);
|
||||||
|
if (HE) {
|
||||||
|
let gone = false; for (let i = 0; i < 40 && !gone; i++) { await sleep(250); gone = !(await (await ctx.request.get(P + '/api/whoami')).json()).address; }
|
||||||
|
ok(gone && HE.view().stats.ended >= 1, '4. the wallet partner session ended too (hub hook member.signedout, matched by the member wallet)', JSON.stringify(HE.view().stats));
|
||||||
|
} else console.log('SKIP 4. wallet-site hook: no ../../5xyourteam/app/hubevents.js');
|
||||||
|
|
||||||
|
// 5. blocked on the hub: no hub sign-in at all
|
||||||
|
const ctx2 = await browser.newContext({ userAgent: UA }); await ctx2.addCookies([{ name: 'iap.sid', value: await codeSignIn(IAP, A), domain: '127.0.0.1', path: '/' }]);
|
||||||
|
const p2 = await ctx2.newPage(); await p2.goto(IAP + '/my'); await p2.waitForTimeout(1500);
|
||||||
|
ok((await ctx2.cookies(HUB)).some(c => c.name === 'hub.sso'), '5. (a fresh browser signs in on the hub again)');
|
||||||
|
// a partner session open in this browser before the block
|
||||||
|
await p2.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team')); await p2.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 }).catch(() => {});
|
||||||
|
const open2 = (await (await ctx2.request.get(P + '/api/whoami')).json()).address === wA;
|
||||||
|
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, reason: 'e2e' });
|
||||||
|
if (HE) {
|
||||||
|
let gone = false; for (let i = 0; i < 40 && !gone; i++) { await sleep(250); gone = !(await (await ctx2.request.get(P + '/api/whoami')).json()).address; }
|
||||||
|
ok(open2 && gone, '5. blocked on the hub: the session open on the wallet partner ends (hub hook member.blocked)', JSON.stringify(HE.view().log.slice(-3)));
|
||||||
|
}
|
||||||
|
const blocked = await ctx2.request.get(HUB + '/sso/check?site=linkspin&st=' + crypto.randomBytes(16).toString('hex') + '&to=%2F', { maxRedirects: 0 });
|
||||||
|
ok(/none=1/.test(blocked.headers()['location'] || '') && /sign-in ended \(blocked/.test(logs.hub + '') || /none=1/.test(blocked.headers()['location'] || ''), '5. blocked on the hub: the hub answers nobody', blocked.headers()['location']);
|
||||||
|
// a hub token replayed: mint one by hand for LinkSpin, spend it, try again
|
||||||
|
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, blocked: false });
|
||||||
|
const ctx3 = await browser.newContext({ userAgent: UA }); const st = crypto.randomBytes(16).toString('hex');
|
||||||
|
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
|
||||||
|
const hubSso = require(path.join(HUB_DIR, 'lib', 'sso.js'));
|
||||||
|
const tok = hubSso.mint(K.linkspin, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
|
||||||
|
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 }); const first = (await meOf(ctx3, LS)).email === A;
|
||||||
|
await ctx3.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||||
|
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]);
|
||||||
|
await ctx3.request.get(LS + '/sso/in?h=' + tok, { maxRedirects: 0 });
|
||||||
|
ok(first && !(await meOf(ctx3, LS)).signedIn && /token already used/.test(logs.ls), '5. a hub token signs in once; the replay is refused');
|
||||||
|
const forged = hubSso.mint(K.iap, { iss: 'hub', aud: 'linkspin', email: A, st, to: '/ads' });
|
||||||
|
await ctx3.addCookies([{ name: 'nsso.st', value: st, domain: 'localhost', path: '/' }]); await ctx3.request.get(LS + '/sso/in?h=' + forged, { maxRedirects: 0 });
|
||||||
|
ok(!(await meOf(ctx3, LS)).signedIn && /refused: signature/.test(logs.ls), '5. a hub token signed with another site\'s key is refused');
|
||||||
|
ok(codeReqs() === codes0 + 2, '5. no email-code request by any network sign-in (only the one setup sign-in in step 5)', (codeReqs() - codes0) + ' requests');
|
||||||
|
ok(!logs.iap.includes(K.iap) && !logs.ls.includes(K.linkspin) && !logs.hub.includes(K.iap), 'no secret in any log');
|
||||||
|
await ctx.close(); await ctx2.close(); await ctx3.close();
|
||||||
|
} catch (e) { origLog('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); fails++; }
|
||||||
|
finally {
|
||||||
|
try { if (browser) await browser.close(); } catch (e) {}
|
||||||
|
for (const s of [srvI, srvL, srvH]) { try { s.kill(); } catch (e) {} } try { partner.close(); } catch (e) {}
|
||||||
|
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
console.log = origLog;
|
||||||
|
if (fails) { for (const k of ['hub', 'iap', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call|^REQ /.test(l)).slice(-20).join('\n')); console.log('--- partner\n' + partnerLog.slice(-10).join('\n')); }
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// Network sign-in from a partner wallet site (5xYourTeam pattern) through InstantAdPay, with the login ad on its clock (2026-11-15).
|
||||||
|
// Same file in InstantAdPay and LinkSpin. node qa/networksso-partner.e2e.mjs
|
||||||
|
// Marty was stranded: 5xYourTeam's "get a position" sent him to sign in through InstantAdPay; IAP answered r=fivex as if LinkSpin
|
||||||
|
// asked, and after a fresh sign-in the login ad's "Go to dashboard" left him on the IAP dashboard. This boots IAP and LinkSpin on
|
||||||
|
// throwaway DATA_DIRs plus a stand-in partner (the same networksso.js as a wallet receiver, self 'fivex', on 127.0.0.2: its own
|
||||||
|
// cookie host) and drives a real browser. Proves:
|
||||||
|
// A. signed in on IAP (wallet linked): partner /sso/start -> straight back to the partner page with a session, no IAP page, no ad
|
||||||
|
// B. signed out: partner -> IAP sign-in -> code -> the login ad -> its finish button says Continue -> back on the partner page,
|
||||||
|
// signed in; the countdown restarted the member's clock (the next ask answers notDue)
|
||||||
|
// C. the login-ad clock on a plain dashboard load: due -> the gate shows, after the countdown it does not show again on reload
|
||||||
|
// D. signed in on LinkSpin (wallet linked): partner via=linkspin -> straight back with a session
|
||||||
|
// No mail key, JSON stores, devCode. Skips when the other repo is not beside this one.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||||
|
const peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
|
||||||
|
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||||
|
if (!PEER) { console.log('SKIP partner sign-in e2e: the other repo was not found. Set NSSO_PEER_DIR.'); process.exit(0); }
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||||
|
const SECRET = crypto.randomBytes(24).toString('hex');
|
||||||
|
const IP = Number(process.env.NSSO_IAP_PORT || 8831), LP = IP + 1, PP = IP + 2;
|
||||||
|
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP;
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
|
||||||
|
const fetch0 = globalThis.fetch;
|
||||||
|
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-partner-'));
|
||||||
|
const logs = { iap: '', ls: '' };
|
||||||
|
function boot(name, dir, port, extra) {
|
||||||
|
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||||
|
NETWORK_SSO_SECRET: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', FIVEX_URL: P }, extra);
|
||||||
|
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||||
|
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||||
|
}
|
||||||
|
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
|
||||||
|
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
|
||||||
|
|
||||||
|
// the stand-in partner: a wallet receiver exactly like 5xYourTeam (self fivex, asks IAP or LinkSpin, sessions by wallet)
|
||||||
|
process.env.NETWORK_SSO_SECRET = SECRET;
|
||||||
|
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||||
|
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)fx\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||||
|
N.init({ self: 'fivex', peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: path.join(TMP), defaultPath: '/team',
|
||||||
|
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||||
|
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||||
|
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'fx.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||||
|
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||||
|
const partner = http.createServer(async (req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x');
|
||||||
|
if (await N.handle(req, res, u)) return;
|
||||||
|
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
|
||||||
|
});
|
||||||
|
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||||
|
|
||||||
|
let ipN = 30;
|
||||||
|
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.8.0.' + (ipN++), 'User-Agent': UA });
|
||||||
|
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||||
|
async function codeSignIn(base, email) {
|
||||||
|
const h = H();
|
||||||
|
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||||
|
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||||
|
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||||
|
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
|
||||||
|
// members have a username (the dashboard asks for one before anything else)
|
||||||
|
const un = 'p' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
|
||||||
|
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||||
|
if (!pr.ok) throw new Error('username on ' + base + ': ' + pr.status + ' ' + (await pr.text()).slice(0, 120));
|
||||||
|
return sid;
|
||||||
|
}
|
||||||
|
// link a throwaway wallet to the signed-in account (the dashboard's Link wallet: challenge, personal_sign, verify)
|
||||||
|
async function linkWallet(base, sid) {
|
||||||
|
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
|
||||||
|
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
|
||||||
|
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
|
||||||
|
const j = await v.json(); if (j.error) throw new Error('wallet link on ' + base + ': ' + j.error);
|
||||||
|
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
|
||||||
|
}
|
||||||
|
const host = base => new URL(base).hostname;
|
||||||
|
let browser = null;
|
||||||
|
async function newCtx(sessions) {
|
||||||
|
const ctx = await browser.newContext({ userAgent: UA });
|
||||||
|
const add = Object.entries(sessions || {}).map(([base, sid]) => ({ name: 'iap.sid', value: sid, domain: host(base), path: '/' }));
|
||||||
|
if (add.length) await ctx.addCookies(add);
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
|
||||||
|
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up: iap ' + a + ', linkspin ' + b); await sleep(500); }
|
||||||
|
browser = await chromium.launch();
|
||||||
|
// a house login ad on IAP (the admin path), so the gate has something to show
|
||||||
|
const hc = await fetch(IAP + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA login sponsor', targetUrl: 'https://example.com/' }) });
|
||||||
|
const hj = await hc.json().catch(() => ({}));
|
||||||
|
ok(hc.ok && !hj.error, 'setup: a house login ad on InstantAdPay', JSON.stringify(hj).slice(0, 160));
|
||||||
|
// signed out (bots, probes, link previews): no login ad drawn and no view counted, on either site
|
||||||
|
const so = await (await fetch(IAP + '/api/ads/slot?type=login')).json();
|
||||||
|
const imps = async () => ((await (await fetch(IAP + '/api/admin/campaigns', { headers: { Authorization: 'Bearer localtest' } })).json()).campaigns || []).filter(c => c.type === 'login').reduce((t, c) => t + (Number(c.imps) || 0), 0);
|
||||||
|
ok(so.signedOut === true && !so.ad && (await imps()) === 0, 'signed out: /api/ads/slot?type=login draws nothing and counts no view on IAP', JSON.stringify(so));
|
||||||
|
const sl = await (await fetch(LS + '/api/ads/slot?type=login')).json();
|
||||||
|
ok(sl.signedOut === true && !sl.ad, 'signed out: nothing on LinkSpin either', JSON.stringify(sl));
|
||||||
|
|
||||||
|
// A. signed in on IAP with a wallet: straight back to the partner page with a session, never an IAP page, no login ad
|
||||||
|
const A = 'partner-a@example.com';
|
||||||
|
const wa = await linkWallet(IAP, await codeSignIn(IAP, A));
|
||||||
|
let ctx = await newCtx({ [IAP]: wa.sid }); let page = await ctx.newPage(); let navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=1#buy')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
let who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team?pick=1#buy' && who.address === wa.address && who.via === 'iap', 'A. signed in on IAP: back on the partner page signed in as the linked wallet', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
ok(!navs.some(u => u.startsWith(IAP + '/my')), 'A. no IAP dashboard and no login ad on the way', navs.join(' , '));
|
||||||
|
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.iap), 'A. IAP logged a token for 5xYourTeam (never "for LinkSpin")');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// B. signed out on IAP: sign in there, the login ad shows, its Continue goes back to the partner page
|
||||||
|
const B = 'partner-b@example.com';
|
||||||
|
const wb = await linkWallet(IAP, await codeSignIn(IAP, B));
|
||||||
|
await fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + wb.sid }), body: '{}' });
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage(); navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=iap&to=' + encodeURIComponent('/team?pick=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||||
|
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'B. signed out: IAP asks for its sign-in and remembers the trip', page.url());
|
||||||
|
await page.fill('#mcEmail', B); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
|
||||||
|
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
|
||||||
|
await page.click('#mcVerifyBtn');
|
||||||
|
await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok(true, 'B. the login ad shows after the fresh sign-in');
|
||||||
|
await page.click('#lgOpen');
|
||||||
|
await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 });
|
||||||
|
ok((await page.textContent('#lgContinue')).trim() === 'Continue', 'B. its finish button continues the trip (not "Go to dashboard")', await page.textContent('#lgContinue'));
|
||||||
|
await page.click('#lgContinue');
|
||||||
|
await page.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team?pick=2' && who.address === wb.address, 'B. back on the partner page it came from, signed in', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
const again = await (await ctx.request.get(IAP + '/api/ads/slot?type=login')).json();
|
||||||
|
ok(again.notDue === true && !again.ad, 'B. the countdown restarted the clock: the next ask on IAP is not due', JSON.stringify(again).slice(0, 120));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// C. the clock on a plain dashboard load (no sign-in on this page): due -> the gate; after the countdown, a reload shows no gate
|
||||||
|
const C = 'partner-c@example.com';
|
||||||
|
const cI = await codeSignIn(IAP, C);
|
||||||
|
ctx = await newCtx({ [IAP]: cI }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok((await page.textContent('#lgContinue')).trim() === 'Go to dashboard', 'C. signed in earlier, first dashboard load: the login ad shows (due), finish says Go to dashboard');
|
||||||
|
const early = await (await ctx.request.post(IAP + '/api/ads/login/seen')).json();
|
||||||
|
ok(early.ok === false && early.reason === 'too soon', 'C. telling the server "seen" before the countdown is refused', JSON.stringify(early));
|
||||||
|
await page.click('#lgOpen', { timeout: 10000 }); await page.waitForSelector('#lgContinue:not([hidden])', { timeout: 20000 }); await page.waitForTimeout(800); await page.click('#lgContinue');
|
||||||
|
ok(await page.locator('#loginGate').isHidden(), 'C. Go to dashboard closes the gate');
|
||||||
|
await page.reload(); await page.waitForTimeout(3500);
|
||||||
|
ok(await page.locator('#loginGate').isHidden(), 'C. a reload inside the setting (3 hours) shows no login ad');
|
||||||
|
const d2 = await ctx.newPage(); await d2.goto(IAP + '/my'); await d2.waitForTimeout(3000);
|
||||||
|
ok(await d2.locator('#loginGate').isHidden(), 'C. nor does another tab');
|
||||||
|
await ctx.close();
|
||||||
|
// and a reload DURING the countdown does not skip it
|
||||||
|
const D0 = 'partner-d0@example.com'; const d0 = await codeSignIn(IAP, D0);
|
||||||
|
ctx = await newCtx({ [IAP]: d0 }); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my'); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 }); await page.click('#lgOpen'); await page.waitForTimeout(2000);
|
||||||
|
await page.reload(); await page.waitForSelector('#loginGate:not([hidden])', { timeout: 15000 });
|
||||||
|
ok(true, 'C. a reload during the countdown brings the login ad back');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// D. signed in on LinkSpin with a wallet: via=linkspin, straight back to the partner
|
||||||
|
const D = 'partner-d@example.com';
|
||||||
|
const wd = await linkWallet(LS, await codeSignIn(LS, D));
|
||||||
|
ctx = await newCtx({ [LS]: wd.sid }); page = await ctx.newPage(); navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&via=linkspin&to=' + encodeURIComponent('/team')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/team' && who.address === wd.address && who.via === 'linkspin', 'D. signed in on LinkSpin: back on the partner page signed in', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
ok(/token issued p\*\*\*@example\.com for 5xYourTeam/.test(logs.ls), 'D. LinkSpin logged a token for 5xYourTeam');
|
||||||
|
// E. LinkSpin's login-ad clock: a house login ad, then the member's clock (served, too soon refused, finished, not due)
|
||||||
|
const lh = await fetch(LS + '/api/admin/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer localtest' }, body: JSON.stringify({ type: 'login', name: 'QA LS login sponsor', targetUrl: 'https://example.com/' }) });
|
||||||
|
const lhj = await lh.json().catch(() => ({}));
|
||||||
|
if (!lh.ok || lhj.error) ok(false, 'E. setup: a house login ad on LinkSpin', lh.status + ' ' + JSON.stringify(lhj).slice(0, 160));
|
||||||
|
else {
|
||||||
|
const lsGet = async () => (await ctx.request.get(LS + '/api/ads/slot?type=login')).json();
|
||||||
|
const lsSeen = async () => (await ctx.request.post(LS + '/api/ads/login/seen')).json();
|
||||||
|
let x = await lsGet(); ok(!!(x.ad && x.ad.targetUrl), 'E. LinkSpin: due -> a login ad', JSON.stringify(x).slice(0, 100));
|
||||||
|
x = await lsSeen(); ok(x.ok === false && x.reason === 'too soon', 'E. LinkSpin: "seen" before the countdown is refused', JSON.stringify(x));
|
||||||
|
await sleep(9000); x = await lsSeen(); ok(x.ok === true, 'E. LinkSpin: after the countdown the clock restarts', JSON.stringify(x));
|
||||||
|
x = await lsGet(); ok(x.notDue === true && !x.ad, 'E. LinkSpin: inside the setting, no login ad', JSON.stringify(x));
|
||||||
|
}
|
||||||
|
await ctx.close();
|
||||||
|
} catch (e) { console.log('FAIL exception', e && e.stack || e, e && e.cause ? 'cause: ' + (e.cause.stack || e.cause) : ''); fails++; }
|
||||||
|
finally {
|
||||||
|
try { if (browser) await browser.close(); } catch (e) {}
|
||||||
|
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {} try { partner.close(); } catch (e) {}
|
||||||
|
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => !/rpc eth_call/.test(l)).slice(-30).join('\n')); }
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
// The way back to a network site after signing in on InstantAdPay (Marty 2026-11-17: "I just logged in to Instant Ad Pay from
|
||||||
|
// Viral Ad Source, and it never had a return path back"). Same file in InstantAdPay and LinkSpin.
|
||||||
|
// node qa/networksso-return.e2e.mjs (needs ../../network-hub and the other site beside this one; skips otherwise)
|
||||||
|
// The partner here is a site InstantAdPay has NO hand-written line for (the ViralAdSource case): only the hub's HUB_SSO_SITES lists
|
||||||
|
// it, and IAP learns it from the hub's public GET /v1/sso-sites. Real hub (JSON store), IAP, LinkSpin, a stand-in wallet partner
|
||||||
|
// (the ViralAdSource shape: email-less, signs in by wallet), each on its own cookie host, driven by a real browser:
|
||||||
|
// 1. signed in nowhere, the partner's silent check: back on the partner's own sign-in page, never dropped on the IAP dashboard
|
||||||
|
// 2. a deliberate tap, signed out on IAP: IAP's sign-in, the code, then back on the exact partner page, signed in by wallet
|
||||||
|
// 3. a deliberate tap, signed in on IAP with no wallet yet: the IAP Wallet tab (no bounce loop), the wallet link, then back
|
||||||
|
// 4. a ?return=<site>&to=/path link on IAP: remembered, the URL cleaned, the code sign-in, then back on that partner page
|
||||||
|
// 5. the same link while signed in: straight back; /go/<site> works for a hub-only site
|
||||||
|
// 6. never an open redirect: an unknown ?return= is ignored, an off-site to= becomes /
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||||
|
const PEER = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||||
|
const HUB_DIR = [process.env.HUB_DIR, path.resolve(HERE, '../../network-hub')].filter(Boolean).find(d => fs.existsSync(path.join(d, 'lib', 'sso.js')));
|
||||||
|
if (!PEER || !HUB_DIR) { console.log('SKIP return e2e: needs the other site and network-hub beside this repo.'); process.exit(0); }
|
||||||
|
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
const { ethers } = require(path.join(IAP_DIR, 'node_modules', 'ethers'));
|
||||||
|
const SITE = 'newsite'; // in no provider's hand-written list
|
||||||
|
const SSO = crypto.randomBytes(24).toString('hex');
|
||||||
|
const K = { iap: crypto.randomBytes(24).toString('hex'), linkspin: crypto.randomBytes(24).toString('hex'), [SITE]: crypto.randomBytes(24).toString('hex') };
|
||||||
|
const IP = Number(process.env.NSSO_IAP_PORT || 8861), LP = IP + 1, PP = IP + 2, HP = IP + 3;
|
||||||
|
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP, P = 'http://127.0.0.2:' + PP, HUB = 'http://127.0.0.3:' + HP;
|
||||||
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-ret-'));
|
||||||
|
const logs = { iap: '', ls: '', hub: '' };
|
||||||
|
function boot(name, dir, port, extra) {
|
||||||
|
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||||
|
NETWORK_SSO_SECRET: SSO, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', DOCSTORE_URL: '', LS_SYNC_SECRET: '', HUB_ENABLED: '', HUB_URL: HUB, HUB_SSO: 'on', HUB_ACTIVITY: '0' }, extra);
|
||||||
|
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||||
|
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||||
|
}
|
||||||
|
const srvH = boot('hub', HUB_DIR, HP, { HUB_URL: '', HUB_SSO: '', HUB_ADMIN_SECRET: crypto.randomBytes(24).toString('hex'),
|
||||||
|
HUB_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, [SITE]: { secret: K[SITE] } }),
|
||||||
|
HUB_SSO_SITES: JSON.stringify({ iap: IAP, linkspin: LS, [SITE]: P }) });
|
||||||
|
// the hub has to answer /v1/sso-sites before IAP and LinkSpin start (they read it at start, and again when an unknown site asks)
|
||||||
|
for (let i = 0; i < 120; i++) { try { if ((await fetch(HUB + '/health')).ok) break; } catch (e) {} await sleep(250); }
|
||||||
|
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS, HUB_SECRET: K.iap, HUB_SITE: 'iap' });
|
||||||
|
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP, HUB_SECRET: K.linkspin, HUB_SITE: 'linkspin' });
|
||||||
|
|
||||||
|
// the stand-in partner (the ViralAdSource shape), hub mode on, in this process
|
||||||
|
Object.assign(process.env, { NETWORK_SSO_SECRET: SSO, HUB_URL: HUB, HUB_SECRET: K[SITE], HUB_SITE: SITE, HUB_SSO: 'on', HUB_ACTIVITY: '0' });
|
||||||
|
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||||
|
const PS = new Map(); const sidOf = req => (/(?:^|;\s*)ns\.sid=([a-f0-9]{32})/.exec(req.headers.cookie || '') || [])[1];
|
||||||
|
const origLog = console.log; const partnerLog = []; console.log = (...a) => { if (a[0] === 'network-sso') partnerLog.push(a.join(' ')); else origLog(...a); };
|
||||||
|
N.init({ self: SITE, peer: 'iap', peerBase: () => IAP, from: { iap: () => IAP, linkspin: () => LS }, isProd: false, dataDir: TMP, defaultPath: '/my',
|
||||||
|
member: async req => { const s = PS.get(sidOf(req)); return s ? { address: s.address } : null; },
|
||||||
|
accept: async (e, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
|
||||||
|
signIn: async (e, req, v) => { const id = crypto.randomBytes(16).toString('hex'); PS.set(id, { address: v.wallet, via: v.iss }); return 'ns.sid=' + id + '; Path=/; HttpOnly; SameSite=Lax'; },
|
||||||
|
landing: to => to, signinPath: to => '/signin?to=' + encodeURIComponent(to) });
|
||||||
|
const partner = http.createServer(async (req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x');
|
||||||
|
if (await N.handle(req, res, u)) return;
|
||||||
|
if (u.pathname === '/api/whoami') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(PS.get(sidOf(req)) || {})); }
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<!doctype html><title>partner</title><p id="pg">' + u.pathname + '</p>');
|
||||||
|
});
|
||||||
|
await new Promise((r, j) => { partner.once('error', j); partner.listen(PP, '127.0.0.2', r); });
|
||||||
|
|
||||||
|
let ipN = 70;
|
||||||
|
const H = () => ({ 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA });
|
||||||
|
const sidFrom = r => ((r.headers.getSetCookie ? r.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid=')) || '').slice('iap.sid='.length);
|
||||||
|
async function codeSignIn(base, email) {
|
||||||
|
const h = H();
|
||||||
|
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||||
|
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||||
|
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||||
|
const sid = sidFrom(v); if (!sid) throw new Error('code sign-in failed on ' + base + ': ' + JSON.stringify(sj) + ' ' + v.status);
|
||||||
|
const un = 'r' + email.split('@')[0].replace(/[^a-z0-9]/g, '').slice(0, 14) + crypto.randomBytes(2).toString('hex');
|
||||||
|
const pr = await fetch(base + '/api/my/profile', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: JSON.stringify({ username: un }) });
|
||||||
|
if (!pr.ok && !(await (await fetch(base + '/api/me', { headers: { Cookie: 'iap.sid=' + sid } })).json()).username) throw new Error('username on ' + base + ': ' + pr.status); // a second sign-in: the name is set already
|
||||||
|
return sid;
|
||||||
|
}
|
||||||
|
async function linkWallet(base, sid) {
|
||||||
|
const w = ethers.Wallet.createRandom(); const h = Object.assign(H(), { Cookie: 'iap.sid=' + sid });
|
||||||
|
const ch = await (await fetch(base + '/api/auth/challenge', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address }) })).json();
|
||||||
|
const v = await fetch(base + '/api/auth/verify', { method: 'POST', headers: h, body: JSON.stringify({ address: w.address, signature: await w.signMessage(ch.message) }) });
|
||||||
|
const j = await v.json(); if (j.error) throw new Error('wallet link: ' + j.error);
|
||||||
|
return { address: w.address.toLowerCase(), sid: sidFrom(v) || sid };
|
||||||
|
}
|
||||||
|
const logout = sid => fetch(IAP + '/api/auth/logout', { method: 'POST', headers: Object.assign(H(), { Cookie: 'iap.sid=' + sid }), body: '{}' });
|
||||||
|
// the IAP dashboard's email-code sign-in, in the browser (the form's 4-second human timer included)
|
||||||
|
async function uiSignIn(page, email) {
|
||||||
|
await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||||
|
await page.fill('#mcEmail', email); await page.waitForTimeout(4600); await page.click('#mcSendBtn');
|
||||||
|
await page.waitForFunction(() => document.getElementById('mcCode') && document.getElementById('mcCode').value.length === 6, null, { timeout: 15000 });
|
||||||
|
await page.click('#mcVerifyBtn');
|
||||||
|
}
|
||||||
|
const whoami = async ctx => (await (await ctx.request.get(P + '/api/whoami')).json());
|
||||||
|
const mainNavs = page => { const n = []; page.on('framenavigated', f => { if (f === page.mainFrame()) n.push(f.url()); }); return n; };
|
||||||
|
let browser = null;
|
||||||
|
const newCtx = async sid => { const c = await browser.newContext({ userAgent: UA }); if (sid) await c.addCookies([{ name: 'iap.sid', value: sid, domain: '127.0.0.1', path: '/' }]); return c; };
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 240; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; if (i === 239) throw new Error('servers not up'); await sleep(500); }
|
||||||
|
await sleep(1500); N._hubSeen();
|
||||||
|
browser = await chromium.launch();
|
||||||
|
const sites = await (await fetch(HUB + '/v1/sso-sites')).json();
|
||||||
|
ok(sites.sites && sites.sites[SITE] === P, 'setup: the hub lists the partner at GET /v1/sso-sites', JSON.stringify(sites));
|
||||||
|
|
||||||
|
// 1. the 2026-11-17 bug: signed in nowhere, the partner's silent check dropped the visitor on the IAP dashboard
|
||||||
|
let ctx = await newCtx(); let page = await ctx.newPage(); let navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=check&to=' + encodeURIComponent('/my')); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(800);
|
||||||
|
ok(page.url() === P + '/signin?to=%2Fmy', '1. signed in nowhere: back on the partner\'s own sign-in page', page.url());
|
||||||
|
ok(!navs.some(u => u.startsWith(IAP + '/my')), '1. never dropped on the InstantAdPay dashboard', navs.map(u => u.slice(0, 60)).join(' , '));
|
||||||
|
ok(!/unknown site asking/.test(logs.iap), '1. IAP knows the hub-only site (no "unknown site asking")');
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 2. a deliberate tap while signed out on IAP: sign in there, then back on the exact partner page
|
||||||
|
const B = 'ret-b@example.com'; const wb = await linkWallet(IAP, await codeSignIn(IAP, B)); await logout(wb.sid);
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage();
|
||||||
|
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?tab=post#new')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||||
|
ok(page.url().startsWith(IAP + '/my') && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), '2. signed out on IAP: IAP asks for its sign-in and remembers the trip', page.url());
|
||||||
|
await uiSignIn(page, B);
|
||||||
|
await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 20000 });
|
||||||
|
let who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/my?tab=post#new' && who.address === wb.address, '2. after the code: back on the exact partner page, signed in by wallet', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 3. signed in on IAP with no wallet yet: the Wallet tab first, no bounce, then the wallet link sends it back
|
||||||
|
const C = 'ret-c@example.com'; const sc = await codeSignIn(IAP, C);
|
||||||
|
ctx = await newCtx(sc); page = await ctx.newPage(); navs = mainNavs(page);
|
||||||
|
await page.goto(P + '/sso/start?mode=go&to=' + encodeURIComponent('/my?c=3')); await page.waitForURL(u => String(u).startsWith(IAP + '/my'), { timeout: 15000 }); await page.waitForTimeout(3500);
|
||||||
|
ok(page.url() === IAP + '/my#wallet' && (await ctx.cookies(IAP)).some(c => c.name === 'nsso.wait'), '3. no wallet yet: the IAP Wallet tab, waiting', page.url());
|
||||||
|
const resumes = navs.filter(u => u.includes('/sso/resume')).length;
|
||||||
|
ok(resumes === 0, '3. the dashboard does not bounce back and forth while it waits', resumes + ' resume hops');
|
||||||
|
await page.waitForFunction(() => /signs you in with your wallet/.test((document.getElementById('status') || {}).textContent || ''), null, { timeout: 8000 }).catch(() => {});
|
||||||
|
const st3 = await page.evaluate(() => (document.getElementById('status') || {}).textContent || '');
|
||||||
|
ok(/newsite signs you in with your wallet/.test(st3) && !/\u2014/.test(st3), '3. one plain line says why and what to do', st3);
|
||||||
|
const w3 = ethers.Wallet.createRandom();
|
||||||
|
const ch = await (await ctx.request.post(IAP + '/api/auth/challenge', { headers: H(), data: { address: w3.address } })).json();
|
||||||
|
const lk = await (await ctx.request.post(IAP + '/api/auth/verify', { headers: H(), data: { address: w3.address, signature: await w3.signMessage(ch.message) } })).json();
|
||||||
|
ok(lk.linked && lk.next === '/sso/resume' && lk.backTo === SITE, '3. the wallet link answers with the way back', JSON.stringify({ next: lk.next, backTo: lk.backTo }));
|
||||||
|
await page.goto(IAP + lk.next); await page.waitForURL(u => String(u).startsWith(P + '/my'), { timeout: 15000 });
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/my?c=3' && who.address === w3.address.toLowerCase(), '3. back on the partner page, signed in with the new wallet', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
await ctx.close();
|
||||||
|
|
||||||
|
// 4. a ?return= link on IAP (a site's "Join free" / "Sign in on InstantAdPay" link), signed out
|
||||||
|
const D = 'ret-d@example.com'; const wd = await linkWallet(IAP, await codeSignIn(IAP, D)); await logout(wd.sid);
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my?x=1&return=' + SITE + '&to=' + encodeURIComponent('/post?y=2')); await page.waitForSelector('#mcEmail', { timeout: 15000 });
|
||||||
|
const ret = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||||
|
ok(!/return=|to=/.test(page.url()) && ret && decodeURIComponent(ret.value) === SITE + '|/post?y=2' && ret.httpOnly, '4. remembered (HttpOnly), the URL cleaned', page.url());
|
||||||
|
await uiSignIn(page, D);
|
||||||
|
await page.waitForURL(u => String(u).startsWith(P + '/post'), { timeout: 20000 });
|
||||||
|
who = await whoami(ctx);
|
||||||
|
ok(page.url() === P + '/post?y=2' && who.address === wd.address, '4. after the code: back on that partner page, signed in', page.url() + ' ' + JSON.stringify(who));
|
||||||
|
ok(!(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '4. the way back is used once');
|
||||||
|
|
||||||
|
// 5. the same link while signed in on IAP: straight back; /go/<site> for a hub-only site
|
||||||
|
const sd = await codeSignIn(IAP, D); const ctx5 = await newCtx(sd); const p5 = await ctx5.newPage();
|
||||||
|
await p5.goto(IAP + '/?return=' + SITE + '&to=' + encodeURIComponent('/team')); await p5.waitForURL(u => String(u).startsWith(P + '/team'), { timeout: 15000 });
|
||||||
|
ok(p5.url() === P + '/team' && (await whoami(ctx5)).address === wd.address, '5. signed in already: straight back, signed in', p5.url());
|
||||||
|
const ctx5b = await newCtx(sd); const p5b = await ctx5b.newPage();
|
||||||
|
await p5b.goto(IAP + '/go/' + SITE + '?to=' + encodeURIComponent('/stats')); await p5b.waitForURL(u => String(u).startsWith(P + '/stats'), { timeout: 15000 });
|
||||||
|
ok(p5b.url() === P + '/stats' && (await whoami(ctx5b)).address === wd.address, '5. /go/<site> signs in on a site only the hub lists', p5b.url());
|
||||||
|
await ctx5.close(); await ctx5b.close(); await ctx.close();
|
||||||
|
|
||||||
|
// 6. never an open redirect
|
||||||
|
ctx = await newCtx(); page = await ctx.newPage();
|
||||||
|
await page.goto(IAP + '/my?return=evil&to=' + encodeURIComponent('/x')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
ok(new URL(page.url()).search === '' && !(await ctx.cookies(IAP)).some(c => c.name === 'nsso.ret'), '6. an unknown ?return= is ignored and the URL cleaned', page.url());
|
||||||
|
await page.goto(IAP + '/my?return=' + SITE + '&to=' + encodeURIComponent('//evil.example/x')); await page.waitForLoadState('domcontentloaded');
|
||||||
|
const r6 = (await ctx.cookies(IAP)).find(c => c.name === 'nsso.ret');
|
||||||
|
ok(r6 && decodeURIComponent(r6.value) === SITE + '|/', '6. an off-site to= becomes /', r6 && decodeURIComponent(r6.value));
|
||||||
|
const r6b = await ctx.request.get(IAP + '/my?return=' + SITE + '&to=%2Fa', { maxRedirects: 0, headers: { 'User-Agent': 'curl/8' } });
|
||||||
|
ok(r6b.status() === 302 && !(r6b.headers()['set-cookie'] || '').includes('nsso.ret'), '6. a bot remembers nothing');
|
||||||
|
await ctx.close();
|
||||||
|
ok(!logs.iap.includes(K.iap) && !logs.hub.includes(K[SITE]), 'no secret in any log');
|
||||||
|
} catch (e) { origLog('FAIL exception', e && e.stack || e); fails++; }
|
||||||
|
finally {
|
||||||
|
try { if (browser) await browser.close(); } catch (e) {}
|
||||||
|
for (const s of [srvI, srvL, srvH]) { try { s.kill(); } catch (e) {} } try { partner.close(); } catch (e) {}
|
||||||
|
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
console.log = origLog;
|
||||||
|
if (fails) { for (const k of ['hub', 'iap']) console.log('--- ' + k + ' log (tail)\n' + logs[k].split('\n').filter(l => /sso/.test(l)).slice(-25).join('\n')); console.log('--- partner\n' + partnerLog.slice(-15).join('\n')); }
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||||
@@ -31,6 +31,9 @@ const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP;
|
|||||||
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again
|
||||||
|
const fetch0 = globalThis.fetch;
|
||||||
|
const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } };
|
||||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-'));
|
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-'));
|
||||||
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
|
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
|
||||||
const SPY = path.join(TMP, 'reqlog.cjs');
|
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||||
@@ -127,7 +130,7 @@ try {
|
|||||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
||||||
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
||||||
await page.reload(); await page.waitForTimeout(2500);
|
await page.reload(); await page.waitForTimeout(2500);
|
||||||
ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
ok(starts.length === 1, 'reload inside 2 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
||||||
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
||||||
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
||||||
await ctx.close();
|
await ctx.close();
|
||||||
@@ -142,7 +145,8 @@ try {
|
|||||||
// a session that expired on the provider: the check answers none
|
// a session that expired on the provider: the check answers none
|
||||||
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
|
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);
|
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');
|
ok(!(await meOf(ctx, LS)).signedIn && page.url().startsWith(IAP + '/my'), 'an expired IAP session on a deliberate tap: IAP asks for its own sign-in first (2026-11-14)', page.url());
|
||||||
|
ok((await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'IAP remembers the unfinished trip while the member signs in');
|
||||||
await ctx.close();
|
await ctx.close();
|
||||||
|
|
||||||
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
||||||
@@ -186,7 +190,7 @@ try {
|
|||||||
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
||||||
await hop(LS + '/sso/in?t=' + old);
|
await hop(LS + '/sso/in?t=' + old);
|
||||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
||||||
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/.$/, c => c === 'A' ? 'B' : 'A');
|
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/^(.*)(.)(.{10})$/, (m, h, c, t) => h + (c === 'A' ? 'Q' : 'A') + t); // a middle character: the last one carries 4 bits, so A<->B could decode the same (a 6% flake)
|
||||||
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
|
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
|
||||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
|
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
|
||||||
// open redirect: an off-site path never leaves the site
|
// open redirect: an off-site path never leaves the site
|
||||||
|
|||||||
@@ -78,14 +78,14 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
|
|||||||
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
||||||
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
||||||
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
||||||
ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page');
|
ok(r.loc === '/my', 'loop guard: a second silent check inside 2 minutes goes straight to the page');
|
||||||
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
||||||
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
||||||
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
||||||
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||||
r = await call(R('/sso/start?to=https://evil.example'));
|
r = await call(R('/sso/start?to=https://evil.example'));
|
||||||
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
||||||
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
|
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=120/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 2-minute guard, off-site path replaced', r.loc);
|
||||||
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
||||||
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
||||||
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
||||||
@@ -95,6 +95,8 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
|
|||||||
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
||||||
const issued = new URL(r.loc).searchParams.get('t');
|
const issued = new URL(r.loc).searchParams.get('t');
|
||||||
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
||||||
|
r = await call(R('/sso/check?st=' + st + '&r=fivex&to=/team', 'sid=tok-a'));
|
||||||
|
ok(r.loc === '/my' && !/sso\/in/.test(r.loc), 'provider: a site it does not know (r=fivex with no wallets entry) gets nothing, never a token for the peer (2026-11-15)', r.loc);
|
||||||
// receiver: a LinkSpin-issued token arriving here
|
// receiver: a LinkSpin-issued token arriving here
|
||||||
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
||||||
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Network Weekend tests (Marty 2026-11-17): WEEKEND500 promo start/end gate, the date-gated chatbot fact, /api/network-deals.
|
||||||
|
// Throwaway DATA_DIR, JSON promo store, test clocks only (promos.setClock, a fixed `now` for the fact); no MySQL, no real member.
|
||||||
|
// Run: node qa/networkweekend.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
|
||||||
|
process.env.DATABASE_URL = ''; process.env.MYSQL_HOST = '';
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const promos = require(path.join(ROOT, 'promos.js'));
|
||||||
|
const { weekendFact } = require(path.join(ROOT, 'weekendfact.js'));
|
||||||
|
const netdeals = require(path.join(ROOT, 'netdeals.js'));
|
||||||
|
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 ' + String(e && e.stack || e).split('\n').slice(0, 4).join('\n ')); } }
|
||||||
|
const T = iso => Date.parse(iso);
|
||||||
|
const OPEN = '2026-11-27T00:00:00-06:00', CLOSE = '2026-12-08T00:00:00-06:00';
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
promos.init({ dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'nwtest-')) });
|
||||||
|
await test('WEEKEND500 is created dormant with starts/expires, maxUses 250', async () => {
|
||||||
|
const r = await promos.create({ code: 'weekend500', credits: 500, maxUses: 250, starts: OPEN, expires: CLOSE, partner: 'Network Weekend', note: 'IAP $20+ pack bundle' });
|
||||||
|
assert.ok(r.ok); assert.strictEqual(r.code.starts, T(OPEN)); assert.strictEqual(r.code.expires, T(CLOSE)); assert.strictEqual(r.code.maxUses, 250); assert.strictEqual(r.code.funder, null);
|
||||||
|
});
|
||||||
|
await test('not open one second before Fri 11-27 00:00 CT, open at it', async () => {
|
||||||
|
promos.setClock(() => T(OPEN) - 1000);
|
||||||
|
assert.strictEqual((await promos.redeem('WEEKEND500', 'a@x.test', 'dashboard')).error, 'That promo code is not open yet.');
|
||||||
|
promos.setClock(() => T(OPEN));
|
||||||
|
const g = await promos.redeem('WEEKEND500', 'a@x.test', 'dashboard'); assert.ok(g.ok); assert.strictEqual(g.credits, 500);
|
||||||
|
});
|
||||||
|
await test('one per account', async () => {
|
||||||
|
promos.setClock(() => T('2026-11-30T23:59:00-06:00'));
|
||||||
|
assert.strictEqual((await promos.redeem('WEEKEND500', 'a@x.test', 'dashboard')).error, 'You already used that promo code.');
|
||||||
|
assert.ok((await promos.redeem('WEEKEND500', 'b@x.test', 'link')).ok);
|
||||||
|
});
|
||||||
|
await test('expired from Tue 12-08 00:00 CT', async () => {
|
||||||
|
promos.setClock(() => T(CLOSE) - 1); assert.ok((await promos.redeem('WEEKEND500', 'c@x.test', 'dashboard')).ok);
|
||||||
|
promos.setClock(() => T(CLOSE) + 1); assert.strictEqual((await promos.redeem('WEEKEND500', 'd@x.test', 'dashboard')).error, 'That promo code has expired.');
|
||||||
|
});
|
||||||
|
await test('re-saving a code without starts keeps its start time; codes without starts open now', async () => {
|
||||||
|
const r = await promos.create({ code: 'WEEKEND500', credits: 500, maxUses: 250, expires: CLOSE }); assert.strictEqual(r.code.starts, T(OPEN));
|
||||||
|
promos.setClock(() => T('2026-11-20T12:00:00-06:00'));
|
||||||
|
await promos.create({ code: 'PLAINCODE', credits: 10 }); assert.ok((await promos.redeem('PLAINCODE', 'a@x.test', 'dashboard')).ok);
|
||||||
|
promos.setClock(null);
|
||||||
|
});
|
||||||
|
await test('maxUses caps redemptions', async () => {
|
||||||
|
promos.setClock(() => T('2026-11-28T12:00:00-06:00'));
|
||||||
|
await promos.create({ code: 'CAP2', credits: 5, maxUses: 2, starts: OPEN, expires: CLOSE });
|
||||||
|
assert.ok((await promos.redeem('CAP2', 'p@x.test')).ok); assert.ok((await promos.redeem('CAP2', 'q@x.test')).ok);
|
||||||
|
assert.strictEqual((await promos.redeem('CAP2', 'r@x.test')).error, 'That promo code has been fully redeemed.');
|
||||||
|
promos.setClock(null);
|
||||||
|
});
|
||||||
|
await test('chatbot fact: absent before Fri 00:00 CT and from Tue 12-08 00:00 CT; deal list only Fri to Mon', async () => {
|
||||||
|
assert.strictEqual(weekendFact(T(OPEN) - 1), ''); assert.strictEqual(weekendFact(T(CLOSE)), '');
|
||||||
|
netdeals._set({ events: [{ id: 'nw', name: 'Network Weekend', startsAt: new Date(T(OPEN)).toISOString(), endsAt: new Date(T('2026-12-01T00:00:00-06:00')).toISOString(), days: {},
|
||||||
|
deals: [{ site: 'iap', name: 'InstantAdPay', text: 'x', byDay: { '2026-11-30': 'Cyber Monday: +30% bonus ad credits on any $20+ pack.' }, note: 'Ad credits buy advertising, not income.' }] }] });
|
||||||
|
const mon = weekendFact(T('2026-11-30T09:00:00-06:00'));
|
||||||
|
assert.match(mon, /LIVE NOW/); assert.match(mon, /Cyber Monday: \+30%/); assert.match(mon, /WEEKEND500/); assert.ok(mon.startsWith('\n'));
|
||||||
|
const tue = weekendFact(T('2026-12-01T00:00:00-06:00')); assert.ok(!/LIVE NOW/.test(tue)); assert.match(tue, /WEEKEND500/);
|
||||||
|
assert.ok(!/—/.test(mon + tue), 'no em dashes'); assert.ok(!/up to/i.test(mon + tue));
|
||||||
|
});
|
||||||
|
await test('GET /api/network-deals answers with self and the cached feed', async () => {
|
||||||
|
let head = null, body = '';
|
||||||
|
netdeals.handle({ headers: {} }, { writeHead: (c, h) => { head = [c, h]; }, end: b => { body = b; } }, 'linkspin');
|
||||||
|
assert.strictEqual(head[0], 200); const j = JSON.parse(body); assert.strictEqual(j.self, 'linkspin'); assert.strictEqual(j.events.length, 1);
|
||||||
|
});
|
||||||
|
console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// ViralAdBlitz "Use one of my spin links" (/api/partner/vab/links op 'spins', Marty 2026-11-15).
|
||||||
|
// Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB) and checks: the signature, the member's
|
||||||
|
// own spin links only (never another account's, never the partner-made tracked text-ad links), the public /r/ url on the
|
||||||
|
// link host, active destination count, paused flag, the hosts list, by username or email, unknown account -> account false.
|
||||||
|
// node qa/partner-vabspins.test.mjs (from the site dir; PORT default 8975)
|
||||||
|
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';
|
||||||
|
|
||||||
|
const PORT = Number(process.env.PORT || 8975); const BASE = 'http://127.0.0.1:' + PORT; const SEC = crypto.randomBytes(32).toString('hex');
|
||||||
|
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'vabspins-qa-'));
|
||||||
|
const now = Date.now();
|
||||||
|
const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' });
|
||||||
|
const accounts = { v: 2, byEmail: { 'one@vab.test': acct('one@vab.test', 'vabone', 930001), 'two@vab.test': acct('two@vab.test', 'vabtwo', 930002) }, byAddress: {}, byCode: {}, joins: 2, positions: {} };
|
||||||
|
for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email;
|
||||||
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
|
||||||
|
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: 'spin-links.test.org,spare-links.test.org' }));
|
||||||
|
const dest = (id, url, active) => ({ id, url, label: '', weight: 1, active: active !== false, added: now });
|
||||||
|
const rot = (id, owner, code, name, dests, extra) => Object.assign({ id, owner, name, code, fallback: '', destinations: dests, created: now, paused: false, nextDest: dests.length + 1 }, extra || {});
|
||||||
|
fs.writeFileSync(path.join(DATA, 'rotator.json'), JSON.stringify({ v: 1, hits: [], conv: [], rotations: [
|
||||||
|
rot(1, 'one@vab.test', 'onespin1', 'My three offers', [dest(1, 'https://a.example.org/'), dest(2, 'https://b.example.org/'), dest(3, 'https://c.example.org/', false)]),
|
||||||
|
rot(2, 'one@vab.test', 'onespin2', 'Resting link', [dest(1, 'https://d.example.org/')], { paused: true }),
|
||||||
|
rot(3, 'one@vab.test', 'onevab42', 'ViralAdBlitz: Grow your list', [dest(1, 'https://e.example.org/')], { partner: 'vab:42' }),
|
||||||
|
rot(4, 'two@vab.test', 'twospin1', 'Someone else', [dest(1, 'https://f.example.org/')])
|
||||||
|
] }));
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NETWORK_SSO_SECRET: SEC, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: 'admin@vab.test' });
|
||||||
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL']) delete env[k];
|
||||||
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] });
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
async function call(body, o = {}) {
|
||||||
|
const raw = JSON.stringify(body); const ts = String(o.ts || Date.now()); const sig = crypto.createHmac('sha256', o.sec || SEC).update('net.v1.' + ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(BASE + '/api/partner/vab/links', { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
|
||||||
|
return Object.assign({ _status: r.status }, await r.json().catch(() => ({})));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
|
||||||
|
let r = await call({ username: 'vabone', op: 'spins' }, { sec: 'y'.repeat(64) }); ok(r._status === 401 && !r.spins, 'a wrong signature is refused', r);
|
||||||
|
r = await call({ username: 'vabone', op: 'spins' }, { ts: now - 3600000 }); ok(r._status === 401, 'an old timestamp is refused', r);
|
||||||
|
r = await call({ username: 'nobody', op: 'spins' }); ok(r._status === 200 && r.account === false && !r.spins && Array.isArray(r.hosts) && r.hosts.includes('spin-links.test.org'), 'no LinkSpin account: account false, no links, the public link hosts', r);
|
||||||
|
r = await call({ username: 'vabone', op: 'spins' });
|
||||||
|
ok(r._status === 200 && r.account && r.username === 'vabone' && r.host === 'spin-links.test.org', 'spins: the account by network username, the clean link host', r);
|
||||||
|
const codes = (r.spins || []).map(x => x.code).sort();
|
||||||
|
ok(JSON.stringify(codes) === JSON.stringify(['onespin1', 'onespin2']), 'only the member\'s own spin links (not the partner-made text-ad link, not another account\'s)', codes);
|
||||||
|
const s1 = (r.spins || []).find(x => x.code === 'onespin1') || {}; const s2 = (r.spins || []).find(x => x.code === 'onespin2') || {};
|
||||||
|
ok(s1.url === 'https://spin-links.test.org/r/onespin1' && s1.name === 'My three offers' && s1.destinations === 2 && s1.paused === false, 'each link: public /r/ url, name, active destinations, not paused', s1);
|
||||||
|
ok(s2.paused === true && s2.destinations === 1, 'a paused link says so', s2);
|
||||||
|
ok(Array.isArray(r.hosts) && r.hosts.includes('spin-links.test.org') && r.hosts.includes('spare-links.test.org') && r.hosts.length >= 3, 'hosts: the app host plus every configured link domain', r.hosts);
|
||||||
|
ok(Object.keys(s1).sort().join(',') === 'code,destinations,name,paused,url', 'no destination urls or other account facts in a link', Object.keys(s1));
|
||||||
|
ok(!('email' in r) && !('stats' in r), 'no email or stats in the answer', Object.keys(r));
|
||||||
|
r = await call({ email: 'two@vab.test', op: 'spins' });
|
||||||
|
ok(r.account && (r.spins || []).length === 1 && r.spins[0].code === 'twospin1', 'by email: the other member sees only their own link', r.spins);
|
||||||
|
const rf = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations;
|
||||||
|
ok(rf.length === 4, 'read only: no link made or changed', rf.length);
|
||||||
|
} catch (e) { fail++; console.error(e); }
|
||||||
|
finally { srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
||||||
|
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// ViralAdSource tracked text-ad links (/api/partner/vas/links, 2026-11-17; the vab wiring with site vas). Same checks as
|
||||||
|
// partner-vablinks.test.mjs, plus account by network username (ViralAdSource sends no email) and the 'spins' list.
|
||||||
|
// Boots server.js on its own port with a throwaway seeded data dir (JSON store, no DB, no mail key, no chain keys) and checks:
|
||||||
|
// the signature, one link per text ad on the member's own account with the "ViralAdSource" source and the ad id as sub-id, an edited
|
||||||
|
// ad link updating the same code, a DownlineHydra link with the same id kept apart, stats per site, unknown partner sites refused.
|
||||||
|
// node qa/partner-vaslinks.test.mjs (from the site dir; PORT default 8976)
|
||||||
|
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';
|
||||||
|
|
||||||
|
const PORT = Number(process.env.PORT || 8976); const BASE = 'http://127.0.0.1:' + PORT; const SEC = crypto.randomBytes(32).toString('hex');
|
||||||
|
let pass = 0, fail = 0; const ok = (c, what, x) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (x !== undefined ? ' -> ' + JSON.stringify(x).slice(0, 400) : '')); } };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'vas-qa-'));
|
||||||
|
const now = Date.now();
|
||||||
|
const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' });
|
||||||
|
const accounts = { v: 2, byEmail: { 'one@dh.test': acct('one@dh.test', 'dhone', 920001), 'two@dh.test': acct('two@dh.test', 'dhtwo', 920002) }, byAddress: {}, byCode: {}, joins: 2, positions: {} };
|
||||||
|
for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email;
|
||||||
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
|
||||||
|
fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: 'spin-links.test.org' }));
|
||||||
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NETWORK_SSO_SECRET: SEC, ADMIN_PASSWORD: 'x'.repeat(16), ADMIN_EMAIL: 'admin@dh.test' });
|
||||||
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'HUB_ENABLED', 'HUB_URL']) delete env[k];
|
||||||
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'ignore', 'ignore'] });
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
async function call(body, o = {}, site = 'vas') {
|
||||||
|
const raw = JSON.stringify(body); const ts = String(o.ts || Date.now()); const sig = crypto.createHmac('sha256', o.sec || SEC).update('net.v1.' + ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(BASE + '/api/partner/' + site + '/links', { method: 'POST', body: raw, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
|
||||||
|
return Object.assign({ _status: r.status }, await r.json().catch(() => ({})));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < 60; i++) { try { if ((await fetch(BASE + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
|
||||||
|
const AD = [{ id: '42', name: 'Grow your list', url: 'https://mylist.example.org/?ref=one' }];
|
||||||
|
let r = await call({ email: 'one@dh.test', op: 'ensure', links: AD }, { sec: 'y'.repeat(64) }); ok(r._status === 401, 'a wrong signature is refused');
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'ensure', links: AD }, {}, 'zz'); ok(r._status === 404 || (r._status >= 400 && !r.links), 'an unknown partner site is not served', r);
|
||||||
|
r = await call({ email: 'nobody@dh.test', op: 'ensure', links: AD }); ok(r._status === 200 && r.account === false, 'no LinkSpin account: account false', r);
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'ensure', links: AD });
|
||||||
|
const c42 = r.links && r.links['42'] && r.links['42'].code;
|
||||||
|
ok(r.account && r.host === 'spin-links.test.org' && /^[a-z0-9]{6}$/.test(c42 || '') && r.links['42'].created, 'ensure: a new link for the ad (id field), clean host', r);
|
||||||
|
ok(r.links['42'].link === 'https://spin-links.test.org/r/' + c42 + '?s1=42&placement=42', 'the link carries the ad id as s1 and placement', r.links['42'].link);
|
||||||
|
const src = JSON.parse(fs.readFileSync(path.join(DATA, 'sources.json'), 'utf8')); const mine = (src.items || src.sources || []).filter(x => x.owner === 'one@dh.test');
|
||||||
|
ok(mine.length === 1 && mine[0].template === 'viraladsource' && mine[0].name === 'ViralAdSource' && r.sourceId === mine[0].id, 'the account has one "ViralAdSource" source (network template)', mine);
|
||||||
|
let rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
|
||||||
|
ok(rot.length === 1 && rot[0].partner === 'vas:42' && rot[0].name === 'ViralAdSource: Grow your list' && rot[0].sourceId === mine[0].id && rot[0].destinations[0].url === AD[0].url, 'the link is tagged vas:42 with that source and points at the ad link', rot);
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ id: '42', name: 'Grow your list', url: 'https://mylist.example.org/?ref=one&v=2' }] });
|
||||||
|
rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
|
||||||
|
ok(r.links['42'].code === c42 && !r.links['42'].created && rot.length === 1 && rot[0].destinations[0].url.endsWith('&v=2'), 'an edited ad link updates the same LinkSpin link', r);
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'ensure', links: [{ program: '42', url: 'https://other.example.org/' }] }, {}, 'dh');
|
||||||
|
rot = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).rotations.filter(x => x.owner === 'one@dh.test');
|
||||||
|
ok(r.links['42'] && r.links['42'].code !== c42 && rot.length === 2 && rot.some(x => x.partner === 'dh:42'), 'a DownlineHydra program with the same id is a separate link', rot.map(x => x.partner));
|
||||||
|
r = await call({ username: 'dhone', op: 'ensure', links: [{ id: '42', name: 'Grow your list', url: 'https://mylist.example.org/?ref=one&v=2' }] });
|
||||||
|
ok(r.account && r.username === 'dhone' && r.links['42'] && r.links['42'].code === c42, 'by network username (no email): the same link', r);
|
||||||
|
r = await call({ username: 'dhone', op: 'spins' });
|
||||||
|
ok(r.account && Array.isArray(r.spins) && r.spins.every(x => x.code !== c42) && Array.isArray(r.hosts) && r.hosts.includes('spin-links.test.org'), 'spins by username leave the partner links out and list the hosts', r);
|
||||||
|
const vab = await call({ email: 'one@dh.test', op: 'stats' }, {}, 'vab');
|
||||||
|
ok(vab.account && Object.keys(vab.stats).length === 0, 'vab stats do not see vas links', vab.stats);
|
||||||
|
const hit = await fetch(BASE + '/r/' + c42 + '?s1=42&placement=42', { redirect: 'manual', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36' } });
|
||||||
|
const loc = hit.headers.get('location') || '';
|
||||||
|
ok(hit.status >= 300 && hit.status < 400 && loc.startsWith('https://mylist.example.org/?ref=one&v=2'), 'the redirect lands on the ad link', [hit.status, loc]);
|
||||||
|
await sleep(300);
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'stats' });
|
||||||
|
ok(r.account && r.stats['42'] && r.stats['42'].hits === 1 && r.stats['42'].unique30 === 1 && Object.keys(r.stats).length === 1, 'vas stats: the ad click, only the vas links', r.stats);
|
||||||
|
r = await call({ email: 'one@dh.test', op: 'stats' }, {}, 'dh');
|
||||||
|
ok(r.account && r.stats['42'] && r.stats['42'].hits === 0, 'dh stats do not see the vas click', r.stats);
|
||||||
|
const rep = JSON.parse(fs.readFileSync(path.join(DATA, 'rotator.json'), 'utf8')).hits.find(h => h.r === rot.find(x => x.partner === 'vas:42').id);
|
||||||
|
ok(rep && rep.sr === mine[0].id && rep.q && rep.q.s1 === '42', 'the click is recorded under the ViralAdSource source with the ad sub-id', rep);
|
||||||
|
} catch (e) { fail++; console.error(e); }
|
||||||
|
finally { srv.kill(); await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }
|
||||||
|
console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);
|
||||||
@@ -5,11 +5,11 @@
|
|||||||
# 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 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 + the network merge (netkb)
|
||||||
# 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 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 netsrc # network sites as traffic sources: the seven fixed network links, ?src= picks the sending site's source, member links get it on first use; partner tracked links (DownlineHydra programs, ViralAdBlitz text ads)
|
# bash qa/run.sh netsrc # network sites as traffic sources: the seven fixed network links, ?src= picks the sending site's source, member links get it on first use; partner tracked links (DownlineHydra programs, ViralAdBlitz text ads, its spin-link picker); the admin house Banner Spins route
|
||||||
# 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)
|
||||||
@@ -69,15 +69,23 @@ elif [ "$MODE" = "launchweek" ]; then
|
|||||||
elif [ "$MODE" = "sso" ]; then
|
elif [ "$MODE" = "sso" ]; then
|
||||||
node qa/networksso.test.cjs || status=1
|
node qa/networksso.test.cjs || status=1
|
||||||
node qa/networksso.e2e.mjs || status=1
|
node qa/networksso.e2e.mjs || status=1
|
||||||
|
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||||
|
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||||
|
node qa/networksso-activity.test.mjs || status=1 # the hub activity ping: a signed-in page load, /api/me + heartbeat + admin portal (seen), once a day, never API/bots (real hub, skips without ../../network-hub)
|
||||||
elif [ "$MODE" = "member" ]; then
|
elif [ "$MODE" = "member" ]; then
|
||||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
|
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; SUGGEST_SEND=0 LOCAL=http://127.0.0.1:8796 node qa/support-suggest.mjs || status=1; }; stop_local 8796
|
||||||
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||||
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||||
|
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||||
|
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||||
|
node qa/networksso-activity.test.mjs || status=1 # the hub activity ping: a signed-in page load, /api/me + heartbeat + admin portal (seen), once a day, never API/bots (real hub, skips without ../../network-hub)
|
||||||
node qa/tank-hold.test.mjs || status=1
|
node qa/tank-hold.test.mjs || status=1
|
||||||
|
node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before
|
||||||
node qa/profile-policy.test.cjs || status=1
|
node qa/profile-policy.test.cjs || status=1
|
||||||
node qa/netconv.test.mjs || status=1
|
node qa/netconv.test.mjs || status=1
|
||||||
node qa/topup-positions.test.cjs || status=1 # a top-up the ad's position cannot cover offers the position that can, then moves the ad there (Michael Camire 2026-11-14)
|
node qa/topup-positions.test.cjs || status=1 # a top-up the ad's position cannot cover offers the position that can, then moves the ad there (Michael Camire 2026-11-14)
|
||||||
node qa/bannerspin-attrib.test.cjs || status=1 # Banner Spin: impression -> click -> the banner shown gets the click (same browser, same connection, script ?x=), rows add up (Michael Camire 2026-11-14)
|
node qa/bannerspin-attrib.test.cjs || status=1 # Banner Spin: impression -> click -> the banner shown gets the click (same browser, same connection, script ?x=), rows add up (Michael Camire 2026-11-14)
|
||||||
|
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15, LS-1021)
|
||||||
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
|
||||||
@@ -88,6 +96,7 @@ elif [ "$MODE" = "hubsync" ]; then
|
|||||||
node qa/hubsync.test.cjs || status=1 # needs a network-hub checkout with /v1/resolve {id}: HUB_DIR=<path>
|
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
|
||||||
|
node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before
|
||||||
elif [ "$MODE" = "nas" ]; then
|
elif [ "$MODE" = "nas" ]; then
|
||||||
node qa/nas-stop.test.cjs || status=1
|
node qa/nas-stop.test.cjs || status=1
|
||||||
node qa/nas-ratio.test.cjs || status=1
|
node qa/nas-ratio.test.cjs || status=1
|
||||||
@@ -100,13 +109,18 @@ elif [ "$MODE" = "netconv" ]; then
|
|||||||
node qa/netconv.test.mjs || status=1
|
node qa/netconv.test.mjs || status=1
|
||||||
elif [ "$MODE" = "netsrc" ]; then
|
elif [ "$MODE" = "netsrc" ]; then
|
||||||
node qa/netsrc.test.mjs || status=1
|
node qa/netsrc.test.mjs || status=1
|
||||||
|
node qa/housespins.test.mjs || status=1 # admin house Banner Spins: admin only, house account only, member code path, idempotent, action log, no session minted
|
||||||
node qa/partner-dhlinks.test.mjs || status=1
|
node qa/partner-dhlinks.test.mjs || status=1
|
||||||
node qa/partner-vablinks.test.mjs || status=1
|
node qa/partner-vablinks.test.mjs || status=1
|
||||||
|
node qa/partner-vabspins.test.mjs || status=1
|
||||||
|
node qa/partner-vaslinks.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
|
||||||
node qa/kb-retrieval.cjs || status=1
|
node qa/kb-retrieval.cjs || status=1
|
||||||
node qa/kb-chat.mjs || status=1
|
node qa/kb-chat.mjs || status=1
|
||||||
|
node qa/netkb-merge.test.cjs || status=1 # the shared network knowledge base: home first, a named site first, labels, fast-path skip (2026-11-15)
|
||||||
|
node qa/netkb-semantic.test.mjs || status=1 # semantic matching via the hub (2026-11-16): route/suggest decisions, fail soft, shared-file parity
|
||||||
elif [ "$MODE" = "earn" ]; then
|
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
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Help desk suggestions (2026-11-16): POST /api/my/support/suggest on a LOCAL copy (bash qa/run.sh member starts it; no hub there,
|
||||||
|
// so the answers come from the BM25 fallback, the path members get when the hub or the model is down). Checks: signed out is refused,
|
||||||
|
// a typed problem gets the matching help answer, short text asks nothing, the contact-support entry is never offered, and a ticket
|
||||||
|
// still sends right after (a suggestion never blocks Send). LinkSpin ships the same file (SUGGEST_SEND=0 there: its desk is IAP's).
|
||||||
|
const B = process.env.LOCAL || 'http://127.0.0.1:8796';
|
||||||
|
let pass = 0, fail = 0; const ok = (c, m, x) => { if (c) pass++; else { fail++; console.log('[bug] support-suggest ' + m + (x ? ' :: ' + x : '')); } };
|
||||||
|
const email = 'sg' + Date.now() + '@example.com'; const ip = '198.51.100.' + (20 + Math.floor(Math.random() * 200));
|
||||||
|
const H = { 'Content-Type': 'application/json', 'X-Forwarded-For': ip, 'User-Agent': 'Mozilla/5.0 SupportSuggestQA' };
|
||||||
|
let cookie = '';
|
||||||
|
async function post(p, b) {
|
||||||
|
const r = await fetch(B + p, { method: 'POST', headers: Object.assign({}, H, cookie ? { Cookie: cookie } : {}), body: JSON.stringify(b) });
|
||||||
|
const sc = typeof r.headers.getSetCookie === 'function' ? r.headers.getSetCookie() : [];
|
||||||
|
if (sc.length) cookie = sc.map(c => c.split(';')[0]).join('; ');
|
||||||
|
return { status: r.status, j: await r.json().catch(() => ({})) };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ok((await post('/api/my/support/suggest', { subject: 'my payout', body: 'never arrived' })).status === 401, 'signed out is refused');
|
||||||
|
const st = await post('/api/auth/email/start', { email, fts: Date.now() - 8000, fage: 8000 });
|
||||||
|
if (st.j.devCode) await post('/api/auth/email/verify', { email, code: st.j.devCode });
|
||||||
|
ok(!!cookie, 'signed in for the test');
|
||||||
|
let r = await post('/api/my/support/suggest', { subject: 'Coinbase', body: 'Can I hook up my Coinbase account to pay for a package?' });
|
||||||
|
ok(r.status === 200 && Array.isArray(r.j.items) && r.j.items.length > 0, 'a typed problem gets suggestions', JSON.stringify(r.j).slice(0, 200));
|
||||||
|
ok(r.j.items && r.j.items.some(i => /coinbase/i.test(i.title + ' ' + i.answer)), 'the matching help answer is offered', (r.j.items || []).map(i => i.id).join());
|
||||||
|
ok(['semantic', 'bm25'].includes(r.j.via), 'answered by the hub or the BM25 fallback (' + r.j.via + ')');
|
||||||
|
ok(r.j.items.every(i => !/(^|[-:])support$/.test(i.id) && i.title && i.answer), 'no contact-support entry, every item has a title and an answer');
|
||||||
|
r = await post('/api/my/support/suggest', { subject: 'hi', body: '' });
|
||||||
|
ok(r.status === 200 && r.j.items.length === 0, 'short text asks nothing');
|
||||||
|
r = await post('/api/my/support/suggest', { subject: 'I want to talk to a real person', body: 'please contact me, I need support from a human' });
|
||||||
|
ok(r.status === 200 && r.j.items.every(i => !/(^|[-:])support$/.test(i.id)), 'asking for a person never suggests the contact-support entry');
|
||||||
|
if (process.env.SUGGEST_SEND !== '0') {
|
||||||
|
const t = await post('/api/my/support', { category: 'Other', subject: 'Coinbase question (QA)', body: 'Can I hook up my Coinbase account to pay for a package? (support-suggest QA)' });
|
||||||
|
ok(t.status === 200 && /^IAP-\d+$/.test(String(t.j.ref || '')), 'the ticket still sends after suggestions', JSON.stringify(t.j).slice(0, 160));
|
||||||
|
}
|
||||||
|
} catch (e) { fail++; console.log('[bug] support-suggest crashed :: ' + e.message); }
|
||||||
|
console.log('support-suggest: ' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
// Holding-tank readiness (2026-11-18): the site module against a REAL local network hub (its own temp data dir, throwaway people),
|
||||||
|
// never production. Checks the entry reasons this site derives from its own records, the signed call, the cache, and that the
|
||||||
|
// hub being down leaves the tank list exactly as it was. No mail module is even loaded.
|
||||||
|
// node qa/tank-readiness.test.mjs (HUB_DIR = the network-hub checkout, default ../../network-hub)
|
||||||
|
import { createRequire } from 'module';
|
||||||
|
import fs from 'fs'; import os from 'os'; import path from 'path'; import assert from 'assert';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const HUB_DIR = process.env.HUB_DIR || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '../../../network-hub');
|
||||||
|
const SECRET = 'q'.repeat(40);
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-rdy-'));
|
||||||
|
process.env.HUB_SITES = JSON.stringify({ iap: { secret: SECRET, seeEmails: true } });
|
||||||
|
process.env.HUB_ADMIN_SECRET = 'z'.repeat(40);
|
||||||
|
delete process.env.DATABASE_URL;
|
||||||
|
|
||||||
|
const hubStore = require(path.join(HUB_DIR, 'lib/store'));
|
||||||
|
const hubPeople = require(path.join(HUB_DIR, 'lib/people'));
|
||||||
|
const hubAct = require(path.join(HUB_DIR, 'lib/activity'));
|
||||||
|
const { start } = require(path.join(HUB_DIR, 'server'));
|
||||||
|
const TR = require('../tankready.js');
|
||||||
|
|
||||||
|
let pass = 0; const ok = (c, m) => { assert.ok(c, m); pass++; console.log(' ok', m); };
|
||||||
|
const DAY = 86400000; const now = Date.now();
|
||||||
|
|
||||||
|
// the hub knows two of the leads: one imported from an old site, one who signed in on LinkSpin yesterday
|
||||||
|
hubPeople.importRows([{ email: 'old@t.test', username: 'oldtimer', joinedAt: now - 500 * DAY }], 'vbb');
|
||||||
|
const live = hubPeople.join({ site: 'iap', email: 'live@t.test', username: 'livewire' }).person;
|
||||||
|
hubAct.record(live.id, 'linkspin', 'signin', now - DAY, now);
|
||||||
|
hubPeople.join({ site: 'iap', email: 'spons@t.test', username: 'sponsorx' });
|
||||||
|
|
||||||
|
const server = await start(0); const port = server.address().port;
|
||||||
|
process.env.HUB_URL = 'http://127.0.0.1:' + port; process.env.HUB_SECRET = SECRET; process.env.HUB_SITE = 'iap'; process.env.HUB_ENABLED = '1';
|
||||||
|
|
||||||
|
// a fake site: accounts, tank waiting list, adoption history, follow records
|
||||||
|
const accts = {
|
||||||
|
'old@t.test': { email: 'old@t.test', username: 'oldtimer', created: now - 3 * DAY, joinedVia: 'hub', joinedRef: 'hub:vbb' },
|
||||||
|
'live@t.test': { email: 'live@t.test', username: 'livewire', created: now - 10 * DAY, joinedVia: 'page', joinedRef: 'viefaucet.com', lastSeen: now - 2 * 3600e3 },
|
||||||
|
'resc@t.test': { email: 'resc@t.test', username: 'rescued1', created: now - 30 * DAY },
|
||||||
|
'dead@t.test': { email: 'dead@t.test', username: 'deadlink', created: now - 30 * DAY },
|
||||||
|
'b4h@t.test': { email: 'b4h@t.test', created: now - 7 * DAY, joinedVia: 'btc4hits', joinedRef: 'btc4hits' },
|
||||||
|
'back@t.test': { email: 'back@t.test', username: 'backagain', created: now - 40 * DAY },
|
||||||
|
'spons@t.test': { email: 'spons@t.test', username: 'sponsorx' }
|
||||||
|
};
|
||||||
|
const waiting = ['old@t.test', 'live@t.test', 'resc@t.test', 'dead@t.test', 'b4h@t.test', 'back@t.test'].map(e => ({ email: e, name: '@' + (accts[e].username || 'x'), joined: accts[e].created, lastSeen: accts[e].lastSeen || 0, wallet: e === 'live@t.test' }));
|
||||||
|
const hist = new Map([
|
||||||
|
['resc@t.test', [{ adopter: 'spons@t.test', ts: now - 4 * DAY, status: 'rescued', closed: null }]],
|
||||||
|
['dead@t.test', [{ adopter: 'dead:gone99', ts: now - 5 * DAY, status: 'rescued', closed: null }]],
|
||||||
|
['back@t.test', [{ adopter: 'spons@t.test', ts: now - 20 * DAY, status: 'rescued' }, { adopter: 'spons@t.test', ts: now - 15 * DAY, status: 'expired', closed: now - 8 * DAY }]]
|
||||||
|
]);
|
||||||
|
let calls = 0;
|
||||||
|
TR.init({ site: 'iap', accounts: { byEmail: async e => accts[e] || null }, tank: { waiting: async () => { calls++; return waiting; }, historyMap: async () => hist }, followGet: () => null });
|
||||||
|
|
||||||
|
console.log('tank readiness: local hub on :' + port);
|
||||||
|
const c = await TR.refresh();
|
||||||
|
ok(c && c.by.size === 6, 'one call returned readiness for all six leads');
|
||||||
|
const get = e => c.by.get(e);
|
||||||
|
ok(get('old@t.test').entry.reason === 'imported' && get('old@t.test').entry.detail.oldSite === 'vbb', 'hub-made account: the hub says imported from ViralBannerBlitz with the old join date');
|
||||||
|
ok(get('live@t.test').entry.reason === 'joined' && get('live@t.test').entry.detail.ref === 'viefaucet.com', 'joined with no sponsor, with the source');
|
||||||
|
ok(get('live@t.test').stage === 'activated' && get('live@t.test').heat.score >= 40, 'wallet linked = Activated, signed in recently = warm or hot (' + get('live@t.test').heat.score + ')');
|
||||||
|
ok(get('live@t.test').last.kind === 'signin' && get('live@t.test').last.site === 'iap', 'last action: the site sign-in 2 hours ago beats the LinkSpin one yesterday');
|
||||||
|
ok(get('resc@t.test').entry.reason === 'rescued' && get('resc@t.test').entry.detail.from === 'sponsorx', 'rescued, naming the sponsor by username');
|
||||||
|
ok(get('dead@t.test').entry.reason === 'sponsor_gone' && !get('dead@t.test').entry.detail.from, 'dead sponsor link: sponsor gone, no name');
|
||||||
|
ok(get('b4h@t.test').entry.reason === 'imported' && get('b4h@t.test').entry.detail.oldSite === 'BTC4Hits', 'BTC4Hits import (not on the hub: the site report alone)');
|
||||||
|
ok(get('back@t.test').entry.reason === 'returned', 'back after an adoption window ended (newest record wins)');
|
||||||
|
ok(get('b4h@t.test').stage === 'new' && get('b4h@t.test').heat.band === 'cold' && get('b4h@t.test').last === null, 'never seen: New, Cold, no activity');
|
||||||
|
const txt = JSON.stringify([...c.by.values()]);
|
||||||
|
ok(!/@t\.test/.test(txt), 'no email in anything the hub sent back');
|
||||||
|
ok(!JSON.stringify(hubStore.all().map(p => p.tankEntry || null)).includes('@'), 'no email stored in the entry facts on the hub');
|
||||||
|
ok(hubPeople.byEmail('live@t.test').tankEntry && hubPeople.byEmail('live@t.test').tankEntry.reason === 'joined', 'the entry fact is recorded on the hub');
|
||||||
|
|
||||||
|
const att = await TR.attach(waiting);
|
||||||
|
ok(att.every(w => w.rd) && calls === 1, 'attach uses the fresh cache, no second call');
|
||||||
|
ok(waiting.every(w => !w.rd), 'the original rows are not changed');
|
||||||
|
|
||||||
|
// the hub goes away: the card shows the rows as before (after the cache is gone)
|
||||||
|
server.close(); TR._reset();
|
||||||
|
const down = await TR.attach(waiting, 1500);
|
||||||
|
ok(down.length === 6 && down.every(w => !w.rd), 'hub down: the same rows, no extras, no error');
|
||||||
|
ok(TR.status().ok === false, 'status says the hub is not answering');
|
||||||
|
process.env.HUB_ENABLED = '0'; TR._reset();
|
||||||
|
ok((await TR.attach(waiting)) === waiting, 'switched off: untouched');
|
||||||
|
console.log('tank readiness: ALL PASSED (' + pass + ')');
|
||||||
|
process.exit(0);
|
||||||
+1
-1
@@ -63,4 +63,4 @@ async function importRows(rows, property) {
|
|||||||
let n = 0; for (const r of rows || []) { if (await upsert(Object.assign({ firstProperty: property || 'instantadpay' }, r))) n++; } return n;
|
let n = 0; for (const r of rows || []) { if (await upsert(Object.assign({ firstProperty: property || 'instantadpay' }, r))) n++; } return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, get, byWallet, byUsername, upsert, all, count, chainUp, importRows };
|
module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => { if (!J.db) J.load(); return J.db; }, save: () => J.save() }, init, get, byWallet, byUsername, upsert, all, count, chainUp, importRows };
|
||||||
|
|||||||
+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=20261115nr"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261117nw"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
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 };
|
||||||
|
|||||||
+27
-4
@@ -100,7 +100,7 @@ function pub(r) {
|
|||||||
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 = convOf(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, kind: r.kind || '', 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 || '',
|
||||||
destinations: r.destinations.map(d => Object.assign({ hours: null, health: null, autoPaused: 0 }, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
|
destinations: r.destinations.map(d => Object.assign({ hours: null, health: null, autoPaused: 0 }, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
|
||||||
hits: hits.length, hits7: hits.filter(h => h.ts >= since7).length, uniques: new Set(hits.map(h => h.v)).size, bots: hits.filter(h => h.bot).length };
|
hits: hits.length, hits7: hits.filter(h => h.ts >= since7).length, uniques: new Set(hits.map(h => h.v)).size, bots: hits.filter(h => h.bot).length };
|
||||||
@@ -124,11 +124,14 @@ function bestHours(r) {
|
|||||||
}
|
}
|
||||||
async function list(owner) { return J.db.rotations.filter(r => r.owner === norm(owner)).map(pub); }
|
async function list(owner) { return J.db.rotations.filter(r => r.owner === norm(owner)).map(pub); }
|
||||||
async function get(owner, id) { const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); return r ? pub(r) : null; }
|
async function get(owner, id) { const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); return r ? pub(r) : null; }
|
||||||
|
// the owner's account (ADMIN_EMAIL) has no link cap (Marty 2026-11-17: "since I am the owner, I don't want a limit on my account")
|
||||||
|
const isOwner = owner => { const a = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); return !!a && norm(owner) === a; };
|
||||||
async function create(owner, body) {
|
async function create(owner, body) {
|
||||||
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the rotation a name.' };
|
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the rotation a name.' };
|
||||||
if (J.db.rotations.filter(r => r.owner === norm(owner)).length >= 100) return { error: 'That is a lot of rotations. Archive some first.' };
|
if (!isOwner(owner) && J.db.rotations.filter(r => r.owner === norm(owner)).length >= 100) return { error: 'That is a lot of rotations. Archive some first.' };
|
||||||
let code = newCode(); while (J.db.rotations.some(r => r.code === code)) code = newCode();
|
let code = newCode(); while (J.db.rotations.some(r => r.code === code)) code = newCode();
|
||||||
const r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name, code, fallback: cleanUrl(body.fallback) || '', destinations: [], created: Date.now(), paused: false, nextDest: 1 };
|
const r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name, code, fallback: cleanUrl(body.fallback) || '', destinations: [], created: Date.now(), paused: false, nextDest: 1 };
|
||||||
|
if (body.kind === 'video') { r.kind = 'video'; if (/^[A-Za-z0-9_.-]{1,40}$/.test(String(body.vref || ''))) r.vref = String(body.vref); } // Video Spin (2026-11-22): set by server.js only, never from a member's request body
|
||||||
J.db.rotations.push(r); J.save(); return { ok: true, rotation: pub(r) };
|
J.db.rotations.push(r); J.save(); return { ok: true, rotation: pub(r) };
|
||||||
}
|
}
|
||||||
async function update(owner, id, body) {
|
async function update(owner, id, body) {
|
||||||
@@ -160,7 +163,7 @@ function ensurePartner(owner, key, name, url, sourceId) {
|
|||||||
const u = cleanUrl(url); if (!u || !/^https:\/\//i.test(u)) return { error: 'Destination must be a full https:// address.' };
|
const u = cleanUrl(url); if (!u || !/^https:\/\//i.test(u)) return { error: 'Destination must be a full https:// address.' };
|
||||||
let r = J.db.rotations.find(x => x.owner === norm(owner) && x.partner === k); let created = false;
|
let r = J.db.rotations.find(x => x.owner === norm(owner) && x.partner === k); let created = false;
|
||||||
if (!r) {
|
if (!r) {
|
||||||
if (J.db.rotations.filter(x => x.owner === norm(owner)).length >= 100) return { error: 'This LinkSpin account already has 100 links.' };
|
if (!isOwner(owner) && J.db.rotations.filter(x => x.owner === norm(owner)).length >= 100) return { error: 'This LinkSpin account already has 100 links.' };
|
||||||
let code = newCode(); while (J.db.rotations.some(x => x.code === code)) code = newCode();
|
let code = newCode(); while (J.db.rotations.some(x => x.code === code)) code = newCode();
|
||||||
r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name: String(name || k).slice(0, 80), code, fallback: '', destinations: [{ id: 1, url: u, label: '', weight: 1, active: true, added: Date.now() }], created: Date.now(), paused: false, nextDest: 2, partner: k };
|
r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name: String(name || k).slice(0, 80), code, fallback: '', destinations: [{ id: 1, url: u, label: '', weight: 1, active: true, added: Date.now() }], created: Date.now(), paused: false, nextDest: 2, partner: k };
|
||||||
J.db.rotations.push(r); created = true;
|
J.db.rotations.push(r); created = true;
|
||||||
@@ -192,6 +195,7 @@ async function addDest(owner, id, body, opts) {
|
|||||||
if (r.destinations.length >= cap) return { error: 'Up to ' + DEST_MAX + ' destinations per rotation.' };
|
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() };
|
||||||
|
if (opts && opts.video) { d.vid = String(opts.video.id); d.poster = String(opts.video.poster || ''); d.vowner = String(opts.video.owner || '').slice(0, 40); } // a Video Spin destination
|
||||||
r.destinations.push(d);
|
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)
|
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) };
|
J.save(); return { ok: true, rotation: pub(r) };
|
||||||
@@ -216,6 +220,13 @@ function pick(r, cell) {
|
|||||||
return live[live.length - 1];
|
return live[live.length - 1];
|
||||||
}
|
}
|
||||||
// the redirect: returns { url, dest } or null (unknown code). Records the hit.
|
// the redirect: returns { url, dest } or null (unknown code). Records the hit.
|
||||||
|
// A pick with no click recorded (Video Spin zone, 2026-11-22): the embedded player asks for a video on every page view, and a page view
|
||||||
|
// is not a click. Same rules as a click: paused or off-hours gives no destination.
|
||||||
|
async function peek(code) {
|
||||||
|
const r = J.db.rotations.find(r => r.code === norm(code)); if (!r) return null;
|
||||||
|
const cell = cellAt(zoneFor(r, '')); const off = !r.paused && !isOn(r.hours, cell);
|
||||||
|
return { rotation: r, dest: (r.paused || off) ? null : pick(r, cell) };
|
||||||
|
}
|
||||||
async function resolve(code, req) {
|
async function resolve(code, req) {
|
||||||
const r = J.db.rotations.find(r => r.code === norm(code)); if (!r) return null;
|
const r = J.db.rotations.find(r => r.code === norm(code)); if (!r) return null;
|
||||||
const ua = String(req.headers['user-agent'] || ''); const bot = BOT.test(ua) || !ua;
|
const ua = String(req.headers['user-agent'] || ''); const bot = BOT.test(ua) || !ua;
|
||||||
@@ -362,6 +373,18 @@ async function claim(demoOwner, newOwner) {
|
|||||||
for (const r of mine) { r.owner = o; delete r.demo; delete r.expires; r.name = r.name === 'My first spin' ? 'My first spin' : r.name; }
|
for (const r of mine) { r.owner = o; delete r.demo; delete r.expires; r.name = r.name === 'My first spin' ? 'My first spin' : r.name; }
|
||||||
if (mine.length) J.save(); return { ok: true, claimed: mine.length };
|
if (mine.length) J.save(); return { ok: true, claimed: mine.length };
|
||||||
}
|
}
|
||||||
|
// member erase (erase.js, 2026-11-15): every spin link the person owns goes, with its clicks (memory and every rot_hits row) and
|
||||||
|
// conversions. dryRun counts only. -> { rotations, hits, conv }
|
||||||
|
async function eraseOwner(email, dryRun) {
|
||||||
|
const e = norm(email); const ids = new Set(J.db.rotations.filter(r => norm(r.owner) === e).map(r => r.id));
|
||||||
|
if (!ids.size) return { rotations: 0, hits: 0, conv: 0 };
|
||||||
|
const list = [...ids]; const memHits = J.db.hits.filter(h => ids.has(h.r)).length; const conv = J.db.conv.filter(c => ids.has(c.r)).length;
|
||||||
|
if (dryRun) { const rows = docstore.isOn() ? await docstore.rowsWhere('rot_hits', '$.r', list, false) : 0; return { rotations: ids.size, hits: Math.max(memHits, rows), conv }; }
|
||||||
|
J.db.rotations = J.db.rotations.filter(r => !ids.has(r.id)); // first: no new click can be counted for them
|
||||||
|
J.db.hits = J.db.hits.filter(h => !ids.has(h.r)); J.db.conv = J.db.conv.filter(c => !ids.has(c.r)); HIT_IX = null; J.save();
|
||||||
|
const rows = docstore.isOn() ? await docstore.rowsWhere('rot_hits', '$.r', list, true) : 0;
|
||||||
|
return { rotations: ids.size, hits: Math.max(memHits, rows), conv };
|
||||||
|
}
|
||||||
function sweepDemos() {
|
function sweepDemos() {
|
||||||
const now = Date.now(); const gone = new Set();
|
const now = Date.now(); const gone = new Set();
|
||||||
J.db.rotations = J.db.rotations.filter(r => { if (r.demo && r.expires && r.expires < now) { gone.add(r.id); return false; } return true; });
|
J.db.rotations = J.db.rotations.filter(r => { if (r.demo && r.expires && r.expires < now) { gone.add(r.id); return false; } return true; });
|
||||||
@@ -395,5 +418,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, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
|
module.exports = { eraseOwner, _json: { state: () => J.db, save: () => J.save() }, init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, peek, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
|
||||||
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource, ensureFixed, ensurePartner, partnerStats };
|
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource, ensureFixed, ensurePartner, partnerStats };
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user