diff --git a/loginadclock.js b/loginadclock.js new file mode 100644 index 0000000..74daf94 --- /dev/null +++ b/loginadclock.js @@ -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 }; diff --git a/networksso.js b/networksso.js index f793737..894d156 100644 --- a/networksso.js +++ b/networksso.js @@ -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). // 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=&to=/path P looks at its OWN member session (never the admin portal). Signed in: // P mints a token bound to R, the state and the email, and sends the browser // to R /sso/in?t=. Not signed in: R /sso/in?none=1&to=/path. @@ -14,7 +14,7 @@ // Outbound links: P GET /go/?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the // secret not set), it is a plain redirect to the other site, so it is always safe to link through. // Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie -// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link), +// 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. // Token: "v1..", 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. @@ -36,10 +36,10 @@ const SKEW = 30 * 1000; // clock skew allowed between the two ser const STATE_AGE = 300; // seconds: the state cookie const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14) const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in -const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes +const TRIED_AGE = 120; // seconds: one silent check per browser per 2 minutes (loop guard only; 30 minutes until 2026-11-15) const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet -const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15) +const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15); fivex = 5xYourTeam (2026-11-15) const WALLET_RE = /^0x[0-9a-f]{40}$/; let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath, @@ -177,6 +177,7 @@ async function handle(req, res, u) { const to = safePath(u.searchParams.get('to'), '/'); const r = String(u.searchParams.get('r') || ''); const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet + if (r && r !== C.peer && !wb) { log('check: unknown site asking, nothing sent', null, r.slice(0, 20)); return go(res, C.defaultPath); } // never answer an unknown site as if the peer asked (2026-11-15: 5xYourTeam was sent to LinkSpin) const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud; const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to); if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none); diff --git a/public/admin.html b/public/admin.html index f2d6108..ae405d1 100644 --- a/public/admin.html +++ b/public/admin.html @@ -550,6 +550,6 @@ - + diff --git a/public/ads.html b/public/ads.html index 21342ca..7cfb027 100644 --- a/public/ads.html +++ b/public/ads.html @@ -75,7 +75,7 @@ - + diff --git a/public/assets/admin.js b/public/assets/admin.js index 12163af..da95b8e 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -1093,7 +1093,7 @@ })); // 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() { const wrap = $('siteForm'); wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '
' + esc(SITE_META[k] || humanize(k)) + '' diff --git a/public/assets/cr-shell.js b/public/assets/cr-shell.js index cb3612f..0c21835 100644 --- a/public/assets/cr-shell.js +++ b/public/assets/cr-shell.js @@ -195,9 +195,11 @@ window.CR = (function () { go.addEventListener('click', 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() { - let seen = false; try { seen = !!sessionStorage.getItem('ls.la'); } catch (e) {} - if (seen) return; try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} + if (laAsked) return; laAsked = true; let ad = null; try { ad = (await get('/api/ads/slot?type=login')).ad; } catch (e) { return; } if (!ad || !ad.targetUrl) return; await new Promise(done => { @@ -210,7 +212,7 @@ window.CR = (function () { back.querySelector('#laOpen').addEventListener('click', () => { 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'; - 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(); }); }); @@ -283,7 +285,10 @@ window.CR = (function () { const small = () => { box.innerHTML = 'Remembered who invited you? Tell us'; $('inviteBack').addEventListener('click', e => { e.preventDefault(); full(); $('inviteWho').focus(); }); }; if (ask.dismissed) small(); else full(); } - async function requireSession(onReady) { let m = await me(); whoPaint(m); themeSync(m); if (m && m.signedIn) { strip(); helpBadge(); tankItem(); m = await ensureUsername(m); await loginAd(); inviteCard(m); return onReady(m); } signInFlow(async r => { whoPaint(r); themeSync(r); strip(); helpBadge(); await loginAd(); me(true).then(inviteCard); onReady(r); }); } + // 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 function sparkline(series) { const s = (series || []).map(Number); if (s.length < 2 || !s.some(Boolean)) return ''; diff --git a/public/conversions.html b/public/conversions.html index 2194a78..c8ecd5c 100644 --- a/public/conversions.html +++ b/public/conversions.html @@ -70,7 +70,7 @@
- + diff --git a/public/credits.html b/public/credits.html index b31c59b..2be3846 100644 --- a/public/credits.html +++ b/public/credits.html @@ -83,7 +83,7 @@ - + diff --git a/public/help.html b/public/help.html index 0cfb31c..70025dc 100644 --- a/public/help.html +++ b/public/help.html @@ -30,7 +30,7 @@
loading
- + diff --git a/public/links.html b/public/links.html index 0315e95..f1942c8 100644 --- a/public/links.html +++ b/public/links.html @@ -270,7 +270,7 @@ - + diff --git a/public/my.html b/public/my.html index ed2a030..05d065a 100644 --- a/public/my.html +++ b/public/my.html @@ -1016,7 +1016,7 @@ - + diff --git a/public/pages.html b/public/pages.html index 5a0f518..f765a7a 100644 --- a/public/pages.html +++ b/public/pages.html @@ -73,7 +73,7 @@ - + diff --git a/public/reports.html b/public/reports.html index ca53947..b19acd4 100644 --- a/public/reports.html +++ b/public/reports.html @@ -90,7 +90,7 @@ - + diff --git a/public/sources.html b/public/sources.html index c204a85..f968c2e 100644 --- a/public/sources.html +++ b/public/sources.html @@ -128,7 +128,7 @@ - + diff --git a/public/team.html b/public/team.html index 038a8f3..011c6d5 100644 --- a/public/team.html +++ b/public/team.html @@ -38,7 +38,7 @@ - + diff --git a/public/traffic-guide.html b/public/traffic-guide.html index 9377eab..cfd6fb1 100644 --- a/public/traffic-guide.html +++ b/public/traffic-guide.html @@ -64,7 +64,7 @@
- + diff --git a/public/wallet.html b/public/wallet.html index fc984d6..a183f0e 100644 --- a/public/wallet.html +++ b/public/wallet.html @@ -36,7 +36,7 @@ - + diff --git a/public/zones.html b/public/zones.html index 5708941..0408e39 100644 --- a/public/zones.html +++ b/public/zones.html @@ -42,7 +42,7 @@ - + diff --git a/qa/networksso-partner.e2e.mjs b/qa/networksso-partner.e2e.mjs new file mode 100644 index 0000000..4b331de --- /dev/null +++ b/qa/networksso-partner.e2e.mjs @@ -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('partner

' + u.pathname + '

'); +}); +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); diff --git a/qa/networksso.e2e.mjs b/qa/networksso.e2e.mjs index 89c6836..ab13808 100644 --- a/qa/networksso.e2e.mjs +++ b/qa/networksso.e2e.mjs @@ -31,6 +31,9 @@ const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP; const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'; let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; }; const sleep = ms => new Promise(r => setTimeout(r, ms)); +// an idle keep-alive socket the server closed (5 s default) while the browser launched: the request never reached it, send again +const fetch0 = globalThis.fetch; +const fetch = async (...a) => { for (let i = 0; ; i++) { try { return await fetch0(...a); } catch (e) { if (i >= 3 || !/ECONNRESET|UND_ERR_SOCKET/.test(String((e.cause && (e.cause.code || e.cause.message)) || ''))) throw e; await sleep(300); } } }; const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-')); // a request log on each server (method + path only), so "no email-code request was made" is checked on the server side const SPY = path.join(TMP, 'reqlog.cjs'); @@ -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 page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows'); await page.reload(); await page.waitForTimeout(2500); - ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)'); + 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); 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(); diff --git a/qa/networksso.test.cjs b/qa/networksso.test.cjs index f5bbea6..81e5407 100644 --- a/qa/networksso.test.cjs +++ b/qa/networksso.test.cjs @@ -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' })); ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces'); r = await call(R('/sso/start?to=/my', 'nsso.tried=1')); - ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page'); + 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')); ok(r.loc === '/my', 'after a sign-out here: no silent check'); r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1')); ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)'); r = await call(R('/sso/start?to=https://evil.example')); const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1]; - ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc); + 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')); ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce'); 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')); 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'); + 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 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)); diff --git a/qa/run.sh b/qa/run.sh index c430851..eddaa5d 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -69,10 +69,12 @@ elif [ "$MODE" = "launchweek" ]; then elif [ "$MODE" = "sso" ]; then node qa/networksso.test.cjs || status=1 node qa/networksso.e2e.mjs || status=1 + node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock 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 node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one) + node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock node qa/tank-hold.test.mjs || status=1 node qa/profile-policy.test.cjs || status=1 node qa/netconv.test.mjs || status=1 diff --git a/server.js b/server.js index d59f700..e7e8c09 100644 --- a/server.js +++ b/server.js @@ -46,6 +46,7 @@ const leaderboard = require('./leaderboard'); const toolkit = require('./toolkit'); const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15) const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15) +const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12) const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22) @@ -648,7 +649,8 @@ async function boot() { wallets: { bannerline: () => String(process.env.BL_URL || 'https://downlinebanners.com').replace(/\/+$/, ''), // Downline Banners by wallet (2026-11-13) vbb: () => String(process.env.VBB_URL || 'https://viralbannerblitz.com').replace(/\/+$/, ''), // Viral Banner Blitz by wallet (2026-11-14) viraladblitz: () => String(process.env.VAB_URL || 'https://viraladblitz.com').replace(/\/+$/, ''), // ViralAdBlitz by wallet (2026-11-15; VAB_URL = staging host until the domain switch) - downlinehydra: () => String(process.env.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, '') }, // DownlineHydra (2026-11-15; DH_URL = https://dh.saasy.top until the domain switch) + downlinehydra: () => String(process.env.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, ''), // DownlineHydra (2026-11-15; DH_URL = https://dh.saasy.top until the domain switch) + fivex: () => String(process.env.FIVEX_URL || 'https://5xyourteam.com').replace(/\/+$/, '') }, // 5xYourTeam by wallet (2026-11-15: it asked with r=fivex and was answered as if InstantAdPay asked) wallet: async s => { const a = await accounts.byEmail(s.email); const addr = String(s.address || (a && a.address) || '').toLowerCase(); return addr ? { address: addr, name: '' } : null; }, member: async req => { // a wallet sign-in carries the address, not the email: find the account that owns the wallet (2026-11-13) const s = await auth.fromRequest(req); if (!s) return null; @@ -669,6 +671,7 @@ async function boot() { signinPath: to => (to === '/' ? '/ads' : to) }); // every Control Room screen shows the sign-in itself accounts.init({ dataDir: DATA_DIR }); ads.init({ dataDir: DATA_DIR, chain }); + loginClock.init({ url: process.env.DATABASE_URL || process.env.DOCSTORE_URL, hours: () => siteConfig().loginAdEveryHours }); mailer.init({ dataDir: DATA_DIR }); messages.init({ dataDir: DATA_DIR }); messages.reclassifyCarryNotices(ADMIN_EMAIL || 'house@linkspin.co').then(n => { if (n) console.log('messages: ' + n + ' carry notices made quiet (notice kind)'); }).catch(() => {}); @@ -770,7 +773,7 @@ async function boot() { 'convtrack.json': { state: convtrack._state, save: convtrack._save }, 'earned.json': ads._earned, 'hubsync.json': { state: hubsync._state, save: hubsync._save }, 'iapsync.json': { state: iapsync._state, save: iapsync._save }, 'mail-intro.json': mailer._intro, 'postbacks.json': postbacks._json, 'registry.json': registry._json, 'rotator.json': rotator._json, 'sponsorfollow.json': { state: followStore._state, save: followStore._save } }, - reload: {}, forget: [email => iapsync._forget(email), email => hubsync._forgetHeld(email)] }); + reload: {}, forget: [email => loginClock.forget(String(email || '').toLowerCase()), email => iapsync._forget(email), email => hubsync._forgetHeld(email)] }); // link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)), notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } }); @@ -877,6 +880,7 @@ function siteConfig() { memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line noPayoutIds: '', // LinkSpin member ids differ from InstantAdPay's (IAP #25 = Jim's compromised wallet; LinkSpin #25 is a real member, cleared 2026-10-15). Positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14) leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover) + loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15) tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11 legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) @@ -3971,12 +3975,19 @@ const server = http.createServer(async (req, res) => { // -- ad engine (spec §8b v1: banners, text, login ads) if (p === '/api/ads/slot' && req.method === 'GET') { const t = String(u.searchParams.get('type') || 'banner'); + // login ads run on the member's clock (loginadclock.js): a signed-in member gets one when the last finished view is older than loginAdEveryHours + let lk = ''; if (t === 'login') { const s = await auth.fromRequest(req).catch(() => null); lk = loginClock.keyOf(s); if (!lk) return json(res, 200, { ad: null, signedOut: true }); if (!(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true }); } // signed out never draws or counts a login ad (2026-11-15) const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req), audiences.matcher(req))); // login ads: the member clicks "Open Ad" (a real, counted click into a // new tab) while the countdown runs on our interstitial page - if (ad && t === 'login') ad.dwell = ads.rates().loginDwellSeconds || 10; + if (ad && t === 'login') { ad.dwell = ads.rates().loginDwellSeconds || 10; if (lk) await loginClock.served(lk); } return json(res, 200, { ad }); } + if (p === '/api/ads/login/seen' && req.method === 'POST') { // the login-ad countdown ended: restart this member's clock + const s = await auth.fromRequest(req).catch(() => null); const k = loginClock.keyOf(s); + if (!k) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await loginClock.seen(k, ads.rates().loginDwellSeconds || 10)); + } m = /^\/api\/ads\/click\/(\d+)$/.exec(p); if (m && req.method === 'GET') { const target = await ads.click(m[1]);