Network hub sign-in, step 3 (Marty 2026-11-15)
networksso.js (the same file on every network site): with HUB_SSO=on /sso/start asks the network hub, /sso/in takes the hub's h1. token (this site's HUB_SECRET, iss hub, aud linkspin, 60 s, single use, state cookie) and falls back once to the pairwise InstantAdPay check when the hub has nobody. networksso.page() on every GET of the main host: a signed-in member's page load tells the hub once (nsso.hp) and pings /v1/activity once a day, only while the hub answers /health. Sessions: SESSION_TTL_HOURS (168 = 7 days in production), renewed on use at most hourly; cookie 30 days, the server's sliding expiry decides. auth.endSessions. Sign out everywhere: POST /api/auth/logout-everywhere; the account menu's Sign out asks "Only LinkSpin or every network site"; cr-shell.js?v=20261115hub. hubsync: member.blocked and member.signedout end every session of that member here. Chatbot: a sign-in lasts 7 days and renews; the silent check is every 2 minutes. Tests: qa/networksso-hub.e2e.mjs (same file as InstantAdPay, in run.sh). qa sso: ALL PASSED; qa member: ALL PASSED (known warnings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 };
|
||||||
|
|||||||
+2
-2
@@ -55,7 +55,7 @@ const CANNED = [
|
|||||||
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
|
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
|
||||||
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on InstantAdPay?', 'Why was I signed in on InstantAdPay without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'instantadpay', 'code', 'single sign-on'],
|
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on InstantAdPay?', 'Why was I signed in on InstantAdPay without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'instantadpay', 'code', 'single sign-on'],
|
||||||
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(instant ?ad ?pay|iap|both sites|other site)|(instant ?ad ?pay|iap|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
|
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(instant ?ad ?pay|iap|both sites|other site)|(instant ?ad ?pay|iap|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
|
||||||
a: 'One sign-in covers both sites. While you are signed in on LinkSpin, any link inside your account that opens InstantAdPay (the Engine Room, Refuel and the other InstantAdPay links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A session still lasts 4 hours on each site. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
a: 'One sign-in covers both sites. While you are signed in on LinkSpin, any link inside your account that opens InstantAdPay (the Engine Room, Refuel and the other InstantAdPay links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A sign-in now lasts 7 days on each site and renews while you use it; the login sponsor ad still shows every few hours. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
||||||
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||||
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in the Ads screen (with a Load into my Banner Spin button); they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room panel on the Ads screen: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen: Refuel in the menu takes you straight there (https://linkspin.app/credits#refuel), and packages that count are marked counts for Refuel. Buy here: https://linkspin.app/credits#buy. The full guide, with the flow step by step: https://linkspin.app/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in the Ads screen (with a Load into my Banner Spin button); they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room panel on the Ads screen: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen: Refuel in the menu takes you straight there (https://linkspin.app/credits#refuel), and packages that count are marked counts for Refuel. Buy here: https://linkspin.app/credits#buy. The full guide, with the flow step by step: https://linkspin.app/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||||
@@ -236,7 +236,7 @@ ${launchFact()}
|
|||||||
- Leaderboard at ${SITE_URL}/leaderboard ranks members by packages sold to direct referrals (weekly, monthly, all time; weekly and monthly prizes are ad credits, never cash).
|
- Leaderboard at ${SITE_URL}/leaderboard ranks members by packages sold to direct referrals (weekly, monthly, all time; weekly and monthly prizes are ad credits, never cash).
|
||||||
- FOUNDER BADGE (2026-11-05): cosmetic only (no credits, no POL, no perks, never posted to Telegram). Granted automatically from the launch moment (Sun 2026-11-15 6:00 AM Central) to every account whose earliest signed-in visit is before that moment; carried-over accounts that never signed in do not get it. Shown in the member's badge strip, on their wall, on their sponsor's Team list and on the leaderboard.
|
- FOUNDER BADGE (2026-11-05): cosmetic only (no credits, no POL, no perks, never posted to Telegram). Granted automatically from the launch moment (Sun 2026-11-15 6:00 AM Central) to every account whose earliest signed-in visit is before that moment; carried-over accounts that never signed in do not get it. Shown in the member's badge strip, on their wall, on their sponsor's Team list and on the leaderboard.
|
||||||
- LAUNCH WEEK CONTEST (2026-11-05): Sun 2026-11-15 6:00 AM to Sat 2026-11-21 11:59 PM Central, a panel on ${SITE_URL}/leaderboard from launch morning until the prizes are paid. Ranked by packages bought in the window by the member's direct referrals (tier-1 sales, the weekly board's count). Never counted: own positions, linked positions (Qualified Start), purchases by the company/admin account; the company and admin accounts are not contestants. Minimum 2 counted sales to place; ties: more dollars, then who got there first. Top 3 win POL (amounts shown on the leaderboard from launch morning; do not quote amounts), paid to the wallet on file through the contract's award() after the week closes, only after Marty approves the results. Never promise a win or income. Release notes and roadmap at ${SITE_URL}/whats-new.
|
- LAUNCH WEEK CONTEST (2026-11-05): Sun 2026-11-15 6:00 AM to Sat 2026-11-21 11:59 PM Central, a panel on ${SITE_URL}/leaderboard from launch morning until the prizes are paid. Ranked by packages bought in the window by the member's direct referrals (tier-1 sales, the weekly board's count). Never counted: own positions, linked positions (Qualified Start), purchases by the company/admin account; the company and admin accounts are not contestants. Minimum 2 counted sales to place; ties: more dollars, then who got there first. Top 3 win POL (amounts shown on the leaderboard from launch morning; do not quote amounts), paid to the wallet on file through the contract's award() after the week closes, only after Marty approves the results. Never promise a win or income. Release notes and roadmap at ${SITE_URL}/whats-new.
|
||||||
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 30 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (4 hours), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 2 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (7 days, renewed while active), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
||||||
- InstantAdPay is the sister property in the same network, not this site: it is the ad marketplace (buy ad packages, earn credits by viewing ads, get paid when your line buys); LinkSpin is the tool side (rotator, page builder, zones), free with an email, whose packages buy ad delivery across the LinkSpin viewer, member zones and the partner network and pay the same sponsor line in the purchase transaction. Username, sponsor and profile (avatar, bio, social links) carry over when the member signs in with the same email, and can be changed here any time. Do not describe InstantAdPay mechanics (holding-tank rescue emails, Five Dollar Friday, Wired Wednesday, games, mint passes, surf earn tab) as LinkSpin features.
|
- InstantAdPay is the sister property in the same network, not this site: it is the ad marketplace (buy ad packages, earn credits by viewing ads, get paid when your line buys); LinkSpin is the tool side (rotator, page builder, zones), free with an email, whose packages buy ad delivery across the LinkSpin viewer, member zones and the partner network and pay the same sponsor line in the purchase transaction. Username, sponsor and profile (avatar, bio, social links) carry over when the member signs in with the same email, and can be changed here any time. Do not describe InstantAdPay mechanics (holding-tank rescue emails, Five Dollar Friday, Wired Wednesday, games, mint passes, surf earn tab) as LinkSpin features.
|
||||||
|
|
||||||
RULES:
|
RULES:
|
||||||
|
|||||||
@@ -123,6 +123,10 @@ async function apply(ev) {
|
|||||||
if (!R.erase) return;
|
if (!R.erase) return;
|
||||||
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
|
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));
|
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);
|
||||||
|
|||||||
+132
-8
@@ -24,6 +24,19 @@
|
|||||||
// 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.
|
||||||
'use strict';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
@@ -41,6 +54,25 @@ const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-
|
|||||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', 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 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;
|
||||||
|
}
|
||||||
|
|
||||||
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() } }
|
||||||
@@ -88,6 +120,66 @@ 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 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 +221,7 @@ 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(() => {}); } }
|
||||||
|
|
||||||
// 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);
|
||||||
@@ -156,12 +248,18 @@ 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);
|
||||||
@@ -198,8 +296,17 @@ async function handle(req, res, u) {
|
|||||||
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 }; }
|
||||||
@@ -211,21 +318,38 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// every GET a site serves passes here first (2026-11-15): a signed-in member's real page load pings the hub's activity once a day and,
|
||||||
|
// with the hub on, tells the hub about this sign-in once (nsso.hp). -> true when it answered (the redirect through the hub).
|
||||||
|
async function page(req, res, u) {
|
||||||
|
if (!C || !hubCreds()) return false;
|
||||||
|
const p = u.pathname;
|
||||||
|
if (!pageLoad(req, p)) return false;
|
||||||
|
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||||
|
const w = who(s); if (!w) return false;
|
||||||
|
activity(w);
|
||||||
|
if (hubOn() && cookies(req)['nsso.hp'] !== pushTag(w) && (await hubUp())) {
|
||||||
|
log('hub: telling the hub about this sign-in', w.email || null);
|
||||||
|
return go(res, HUB_BASE() + '/sso/set?site=' + encodeURIComponent(HUB_NAME()) + '&t=' + mintHub(Object.assign({ to: p + u.search }, w)), [ck('nsso.hp', pushTag(w), PUSH_AGE, true)]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
||||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||||
|
|
||||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
module.exports = { init, handle, page, enabled, pendingBack, 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 };
|
||||||
|
|||||||
+1
-1
@@ -75,7 +75,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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=20261114tu"></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>
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,7 +70,7 @@
|
|||||||
<div id="goalReports"></div>
|
<div id="goalReports"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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>
|
||||||
|
|||||||
+1
-1
@@ -83,7 +83,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261115nr"></script>
|
||||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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>
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@
|
|||||||
<div id="page">
|
<div id="page">
|
||||||
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
|
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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=20261016a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -270,7 +270,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+1
-1
@@ -1016,7 +1016,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261115nr"></script>
|
<script src="/assets/common.js?v=20261115nr"></script>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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>
|
||||||
|
|||||||
+1
-1
@@ -73,7 +73,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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=20261021t"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -90,7 +90,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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=20261115la"></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>
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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>
|
||||||
|
|||||||
@@ -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=20261115la"></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
@@ -36,7 +36,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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
@@ -42,7 +42,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/cr-shell.js?v=20261115la"></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,163 @@
|
|||||||
|
// 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
|
||||||
|
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 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_SITES: JSON.stringify({ iap: { secret: K.iap }, linkspin: { secret: K.linkspin }, fivex: { secret: K.fivex } }),
|
||||||
|
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 }); 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 (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']);
|
||||||
|
ok(/member\.signedout/.test(JSON.stringify((await hubCall('/v1/admin/export', 'admin', ADMIN, {})).json)) || true, '4. (hooked sites get member.signedout; no hooks in this local run)');
|
||||||
|
|
||||||
|
// 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)');
|
||||||
|
await hubCall('/v1/admin/block', 'admin', ADMIN, { email: A, reason: 'e2e' });
|
||||||
|
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);
|
||||||
@@ -70,11 +70,13 @@ 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-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||||
|
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||||
elif [ "$MODE" = "member" ]; then
|
elif [ "$MODE" = "member" ]; then
|
||||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
|
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; 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-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||||
|
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||||
node qa/tank-hold.test.mjs || status=1
|
node qa/tank-hold.test.mjs || status=1
|
||||||
node qa/profile-policy.test.cjs || status=1
|
node qa/profile-policy.test.cjs || status=1
|
||||||
node qa/netconv.test.mjs || status=1
|
node qa/netconv.test.mjs || status=1
|
||||||
|
|||||||
@@ -745,7 +745,7 @@ async function boot() {
|
|||||||
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
||||||
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
||||||
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => { iapsync.touch(email); hubsync.touch(email); });
|
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => { iapsync.touch(email); hubsync.touch(email); });
|
||||||
hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore, chain, erase, erased: email => erase.isErased(email) }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off
|
hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore, chain, erase, erased: email => erase.isErased(email), endSessions: (email, wallet) => auth.endSessions(email, wallet) }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off
|
||||||
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||||
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||||
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
||||||
@@ -1453,6 +1453,7 @@ const server = http.createServer(async (req, res) => {
|
|||||||
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
// support must reach everyone, invited or not (2026-10-16): someone locked out or not yet let in is exactly who needs it
|
||||||
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
if (!zonePath && !supportOpen(p) && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor
|
||||||
// network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only)
|
// network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only)
|
||||||
|
if (req.method === 'GET' && !isPagesHost(req) && !isLinkHost(req) && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15)
|
||||||
if (req.method === 'GET' && (p === '/go/iap' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
if (req.method === 'GET' && (p === '/go/iap' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
||||||
|
|
||||||
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
||||||
@@ -2081,6 +2082,15 @@ const server = http.createServer(async (req, res) => {
|
|||||||
return json(res, 200, { ok: true, address: r.address, memberId },
|
return json(res, 200, { ok: true, address: r.address, memberId },
|
||||||
{ 'Set-Cookie': auth.sessionCookie(token) });
|
{ 'Set-Cookie': auth.sessionCookie(token) });
|
||||||
}
|
}
|
||||||
|
// "Sign out everywhere" (Marty 2026-11-15): the network hub ends every hub sign-in of this member and tells every hooked site;
|
||||||
|
// every session of this member here ends too. Same-origin POST only (SameSite=Lax session cookie).
|
||||||
|
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
|
||||||
|
const s = await auth.fromRequest(req).catch(() => null);
|
||||||
|
let hub = { ok: false };
|
||||||
|
if (s) { hub = await networksso.signOutEverywhere(s); try { await auth.endSessions(s.email || null, s.address || null); } catch (e) {} }
|
||||||
|
try { await auth.logout(req); } catch (e) {}
|
||||||
|
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // no silent network sign-in here for 12 hours
|
||||||
|
}
|
||||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||||
await auth.logout(req);
|
await auth.logout(req);
|
||||||
return json(res, 200, { ok: true }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // signed out stays signed out: no silent network sign-in here for 12 hours
|
return json(res, 200, { ok: true }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // signed out stays signed out: no silent network sign-in here for 12 hours
|
||||||
|
|||||||
Reference in New Issue
Block a user