Network hub sign-in, step 3 (Marty 2026-11-15) + signed-out login slot refused
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 iap, 60 s, single use, state cookie), and when the hub has nobody the old pairwise provider is tried once (the fallback until every site is switched). networksso.page() on every GET: a signed-in member's real page load tells the hub once (nsso.hp, hub /sso/set and straight back) and pings the hub's /v1/activity once a day (fire and forget), only while the hub answers /health. Sessions: SESSION_TTL_HOURS (168 = 7 days in production), renewed on use at most hourly; the cookie lives 30 days and the server's sliding expiry decides. auth.endSessions(email, wallet). Sign out everywhere: POST /api/auth/logout-everywhere (hub /v1/sso/signout, every session of the member here ends) and a "Sign out everywhere" link beside Log out; my.js?v=20261115hub. hubsync: member.blocked and member.signedout end every session of that member here. Login ad: /api/ads/slot?type=login refuses signed-out callers (no ad drawn, no view counted; bots and probes cannot run up an advertiser's numbers). The games' kit keeps its own route. Chatbot: a sign-in lasts 7 days and renews; the login ad shows every few hours on its own clock; the silent check is every 2 minutes. Tests: qa/networksso-hub.e2e.mjs (new, run.sh member; real hub + IAP + LinkSpin + a wallet partner on four cookie hosts): page load pushes to the hub once, LinkSpin signs in through the hub, partner gets the wallet from the hub, sign out everywhere, blocked, replay, forged key, no email code. Partner e2e: signed-out slot on both sites, LinkSpin clock. qa member: ALL PASSED (2 known admin warnings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -58,7 +58,9 @@ const J = {
|
||||
this.sessions.set(token, Object.assign({}, s, fields));
|
||||
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 ----
|
||||
@@ -84,7 +86,9 @@ const D = {
|
||||
vals.push(token);
|
||||
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;
|
||||
|
||||
@@ -143,7 +147,7 @@ async function verifyChallenge(address, signature) {
|
||||
async function mintSession(fields) { return impl().mint(fields || {}); }
|
||||
async function updateSession(token, fields) { return impl().update(token, fields || {}); }
|
||||
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'; }
|
||||
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
||||
@@ -153,6 +157,9 @@ async function fromRequest(req) {
|
||||
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||
if (!m) return null;
|
||||
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) {} }
|
||||
return s;
|
||||
}
|
||||
@@ -177,4 +184,5 @@ async function logout(req) {
|
||||
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 };
|
||||
|
||||
+5
-5
@@ -53,7 +53,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)
|
||||
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on LinkSpin?', 'Why was I signed in on LinkSpin without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'linkspin', 'code', 'single sign-on'],
|
||||
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(linkspin|both sites|other site)|(linkspin|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
|
||||
a: 'One sign-in covers both sites. While you are signed in on InstantAdPay, any link inside your account that opens LinkSpin (the Engine Room, Refuel and the other LinkSpin links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A session still lasts 4 hours on each site. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
||||
a: 'One sign-in covers both sites. While you are signed in on InstantAdPay, any link inside your account that opens LinkSpin (the Engine Room, Refuel and the other LinkSpin links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A sign-in now lasts 7 days on each site and renews while you use it; the login sponsor ad still shows every few hours. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
||||
// Stack POL (2026-11-09): stackpol.com, every POL payout across the network on one page; members opt in to a page in Promo tools
|
||||
// Earners Corner (2026-11-10): earnerscorner.com, the network's forum; sign-in is the InstantAdPay account (DiscourseConnect)
|
||||
{ id: 'earners-corner', title: 'Earners Corner forum', q: ['What is Earners Corner?', 'Is there a forum?', 'How do I sign in to the forum?'], tags: ['earners corner', 'forum', 'earnerscorner', 'community', 'discussion'],
|
||||
@@ -172,9 +172,9 @@ const CANNED = [
|
||||
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
|
||||
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
|
||||
// signed out, and the honest answer reads far better than letting it look like a fault.
|
||||
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||
{ id: 'session-4h', title: 'How long does a sign-in last?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||
re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
||||
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
|
||||
a: 'A sign-in lasts 7 days and renews while you use the site, and signing in on any network site signs you in on the others. If you are signed out, sign in again with a fresh code or open the site from another network site you are signed in on - nothing about your account, your credits or your line is affected. The login sponsor ad shows again every few hours whether or not you signed in; that is part of what keeps the free side of the platform paid for. Signing out on a site signs you out of that site only; Sign out everywhere ends it on every network site.' },
|
||||
{ id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'],
|
||||
re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
||||
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
|
||||
@@ -372,7 +372,7 @@ function systemPrompt(kbBlock) {
|
||||
|
||||
FACTS:
|
||||
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company-paid, off-chain decision, on-chain payment. 3% of every package purchase (the POL actually paid) goes to the buyer's 4th upline on the contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = direct referral with a $20+ purchase, same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; the company account (#1) or no qualified upline = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId), shown in Earnings as 'Level 4 override' with a Polygon link and announced by email and an on-site notice. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split 50/20/10 is unchanged. Never promise amounts.
|
||||
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 30 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (4 hours), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
||||
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 2 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (7 days, renewed while active), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
||||
- EARNERS CORNER (LIVE 2026-11-10, https://earnerscorner.com): the network's own forum (Discourse) for people who earn online: business opportunities, PTC, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing, tools, plus an Our Network section. Read is open to everyone; posting needs signing in with the InstantAdPay account (no separate forum password). New accounts' first posts are reviewed; links unlock with trust and are open from day one for members with an on-chain position; referral links only in Promote Your Program; AI spam detection; a forum assistant answers network questions from the same official knowledge and links threads.
|
||||
- STACK POL (LIVE 2026-11-09, https://stackpol.com): one site that adds up every POL payout in the network (InstantAdPay and LinkSpin TierPaid referral payments plus every game's payouts), refreshed every 5 minutes, with per-program pages (/earn/<program>), a public ledger showing each payout's username and Polygonscan link, and a blog. Members get a public page at stackpol.com/<username> by switching on 'Show my Stack POL page' in Promo tools > Stack POL; it is ON by default for every paid member (since 2026-11-09) and off only when they switch it off. It never holds money. STACK POL PRO (2026-11-09): one-time unlock, NEW MONEY only: ANY package of $10 or more bought by the member's own position unlocks it automatically (since 2026-11-09 evening, no order step); credits never count; it never uses up a package that also fulfils a Game Pass or hero order. Pro pages show the member's own LinkSpin Banner Spins in the ad spots (network zones otherwise), their spin links, a purple QR code to the page, a 'Want a personalized page like this?' button, and articles opened from the page (?ref=<username>) use the member's referral on every call to action. Pro owners get the Stack POL Pro badge. Totals are past payouts, never a promise of earnings.
|
||||
${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${warpwaresFact()}${bixFact()}${turkeydropFact()}${sovTestFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||
@@ -382,7 +382,7 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- CONVERSION LINKAGE (LIVE 2026-11-07, reporting only: it never changes sponsors, payouts, credits or anything on chain): a LinkSpin click id (lsclk or lsid in the address) arriving on any InstantAdPay page is kept 30 days in a first-party cookie (last click wins) and travels with the code request, and is stored with the account at sign-up, in-game sign-in included when the game passes it on. InstantAdPay then reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and each purchase on its own, for the click's owner. The landing tag adds the click id to links to instantadpay.com, linkspin.app and the share domains, also inside a member's own redirect link; a spin link or Banner Spin pointed straight at those sites carries it with no goal needed. 30 days from the click to the event, same as goals. The first account on a click owns it. The click owner's own account and own clicks are never counted. People who joined before 2026-11-07 cannot be matched afterwards. Shown on the Conversion tracking card (with goals, 30 days) and in LinkSpin under Reports, Conversions.
|
||||
- CONVERSION TRACKING (LIVE 2026-10-23): Campaigns > Conversion tracking in /my#campaigns. Every click on a member's ad (through /api/ads/click) gets a click id added to the target address as lsclk=<id>; the advertiser adds a goal (name like subscriber or sale, optional default value), puts the LinkSpin landing tag (t.js) on the page the ad points to and the goal pixel (cv.gif image, or the cv.js script) on the thank-you page. LinkSpin (sister site, same email) counts the goals; matching order: click id in the address (url, surest), the id the landing tag stored (stored), LinkSpin's cookie (cookie), a 24-hour match on hashed IP plus browser (soft, least sure). Each goal counts once per click, only within 30 days of a real click, only for the pixel owner's own ads; the advertiser's own clicks (signed in, or from a browser they sign in from; their linked positions share their email so count as them too) and the Send a test conversion button count as tests, never in the numbers; the card shows 'N from your own clicks, kept as tests'. SEND A TEST CONVERSION (2026-10-26) loads the member's real LinkSpin pixel in test mode from their browser (falls back to the signed partner call if the browser blocks it), so Last test updates. Each campaign row shows goals and COST PER GOAL (30 DAYS) in credits (2026-10-26: the credits the campaign spent in the last 30 days, from the credit activity log, divided by its goals in the same 30 days; a campaign started inside the window uses its spend since start; never quote it in dollars). Autoresponder tip: set the Aweber or GetResponse thank-you (success) page to a page on the member's own site carrying the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL); if they cannot, the cookie or the 24-hour match can still count it, less surely. Privacy: the click id is random and nothing personal is sent. SETUP GUIDE (public, 2026-10-24): https://instantadpay.com/conversion-tracking (LinkSpin's copy: https://linkspin.app/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, Last test updates, then remove it), what to do without code on the thank-you page, how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest). Send members there for any setup question.
|
||||
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Since 2026-10-23 the same $5+ Friday package also gives a FREE 7-day Game Pass automatically (once per member per Friday; not a second week when that package itself fulfils a pass order; the Game Pass badge posts the first time). Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
||||
- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report.
|
||||
- SESSIONS LAST 7 DAYS (since 2026-11-15) and renew while the member is active; the network hub keeps one sign-in across every network site, and Sign out everywhere ends all of them. The login sponsor ad no longer depends on signing in: it shows on the next member page once the last finished view is more than a few hours old (a site setting, 3 hours by default). That ad is part of what pays for the free side. Nothing is lost when a session ends - credits, line and account are untouched. Never describe it as a bug.
|
||||
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
||||
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
||||
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
|
||||
|
||||
@@ -145,6 +145,14 @@ async function apply(ev) {
|
||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||
if (ev.type === 'wallet.connected') return walletConnected(ev);
|
||||
if (ev.type === 'member.erased') return memberErased(ev);
|
||||
// network sign-in (2026-11-15): a member the hub blocked, or who chose "Sign out everywhere" on any site, is signed out here too
|
||||
if (ev.type === 'member.blocked' || ev.type === 'member.signedout') {
|
||||
if (!R.endSessions) return 'ignored';
|
||||
const p = await resolve({ id: ev.personId }); if (!p || !p.email) return 'ignored';
|
||||
const n = await R.endSessions(p.email, p.wallet || null);
|
||||
note({ type: ev.type === 'member.blocked' ? 'blocked-signed-out' : 'signed-out-everywhere', sessions: n });
|
||||
return n ? 'applied' : 'ignored';
|
||||
}
|
||||
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
|
||||
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
|
||||
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
|
||||
|
||||
+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
|
||||
// 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.
|
||||
//
|
||||
// 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';
|
||||
const crypto = require('crypto');
|
||||
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 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 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,
|
||||
// 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) };
|
||||
}
|
||||
|
||||
// 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),
|
||||
// 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;
|
||||
@@ -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 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)
|
||||
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 via = String(u.searchParams.get('via') || '');
|
||||
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
||||
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) {}
|
||||
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off']) && !u.searchParams.get('nohub')) return go(res, to);
|
||||
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)];
|
||||
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);
|
||||
@@ -198,8 +296,17 @@ async function handle(req, res, u) {
|
||||
if (p === '/sso/in') {
|
||||
const c = cookies(req);
|
||||
const set = [ck('nsso.st', '', 0, true)];
|
||||
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
||||
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||
if (u.searchParams.get('none')) {
|
||||
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 (!(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 }; }
|
||||
@@ -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); }
|
||||
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
|
||||
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)
|
||||
}
|
||||
if (p === '/api/sso/status') {
|
||||
const c = cookies(req); const set = [];
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
const signedIn = !!(s && (s.email || s.address));
|
||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
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)); }
|
||||
return sendJson(res, out, set);
|
||||
}
|
||||
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
|
||||
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 };
|
||||
|
||||
@@ -3477,6 +3477,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); }
|
||||
catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); }
|
||||
});
|
||||
if ($('logoutAllLink')) $('logoutAllLink').addEventListener('click', async e => { // every network site (2026-11-15)
|
||||
e.preventDefault();
|
||||
let r = {}; try { r = await (await fetch('/api/auth/logout-everywhere', { method: 'POST' })).json(); } catch (er) {}
|
||||
IAP.status(r.everywhere ? 'Signed out on every network site.' : 'Signed out here. The other network sites could not be reached just now, so sign out there too.', r.everywhere ? 'ok' : 'bad');
|
||||
await render();
|
||||
});
|
||||
$('logoutLink').addEventListener('click', async e => {
|
||||
e.preventDefault();
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
|
||||
+2
-1
@@ -168,6 +168,7 @@
|
||||
<div class="bo-foot">
|
||||
<span id="navWallet" class="small muted">…</span>
|
||||
<a href="#" id="logoutLink" class="small">Log out</a>
|
||||
<a href="#" id="logoutAllLink" class="small" title="Signs you out of every network site">Sign out everywhere</a>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -1311,7 +1312,7 @@
|
||||
<script src="/assets/promo.js?v=20261103gp"></script>
|
||||
<script src="/assets/support.js?v=20261115cb"></script>
|
||||
<script src="/assets/netkits.js?v=20261115nk"></script>
|
||||
<script src="/assets/my.js?v=20261115la"></script>
|
||||
<script src="/assets/my.js?v=20261115hub"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script><script src="/assets/tankfeed.js?v=20261115tb"></script>
|
||||
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||
<script src="/assets/netsso.js?v=20261113sso"></script>
|
||||
|
||||
@@ -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);
|
||||
@@ -108,6 +108,12 @@ try {
|
||||
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';
|
||||
@@ -174,6 +180,18 @@ try {
|
||||
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 {
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -67,11 +67,13 @@ 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
|
||||
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
|
||||
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/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||
node qa/tank-hold.mjs || status=1
|
||||
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
|
||||
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
|
||||
|
||||
@@ -762,7 +762,7 @@ async function boot() {
|
||||
reload: { 'legacy.json': () => legacy.reload(), 'legacy-grants.json': () => legacy.reload() },
|
||||
forget: [email => loginClock.forget(String(email || '').toLowerCase()), email => lssync._forget(email), email => { if (hubsync.enabled()) hubsync._forgetHeld(email); }] });
|
||||
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase, endSessions: (email, wallet) => auth.endSessions(email, wallet) }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
|
||||
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
|
||||
await draftpartner.init({ maxOpen: () => siteConfig().fiveXDraftCap, dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
|
||||
@@ -2396,6 +2396,7 @@ const server = http.createServer(async (req, res) => {
|
||||
res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end();
|
||||
} }
|
||||
// network sign-in with LinkSpin (2026-11-12): /go/linkspin, /sso/start, /sso/check, /sso/in, /api/sso/status
|
||||
if (req.method === 'GET' && 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/linkspin' || p === '/go/bannerline' || p === '/go/vbb' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||
// network member lookup for Downline Banners (2026-11-13, Marty: share links use the InstantAdPay username): ?u=<username> -> the
|
||||
// account's linked wallet, ?a=<wallet> -> the username. Public data only (usernames are public join links, wallets are on-chain).
|
||||
@@ -3064,6 +3065,15 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true, address: r.address, memberId },
|
||||
{ '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 h
|
||||
}
|
||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||
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
|
||||
@@ -5558,7 +5568,8 @@ const server = http.createServer(async (req, res) => {
|
||||
if (t === 'login') { // on the member's clock (loginadclock.js); back = a network sign-in hop to finish when the countdown ends (2026-11-15)
|
||||
const s = await auth.fromRequest(req).catch(() => null); const lk = loginClock.keyOf(s);
|
||||
const back = networksso.pendingBack(req) ? '/sso/resume' : null;
|
||||
if (lk && !(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true, back });
|
||||
if (!lk) return json(res, 200, { ad: null, signedOut: true }); // signed out (bots, probes, link previews) never draws or counts a login ad (2026-11-15); the games' kit has its own route
|
||||
if (!(await loginClock.due(lk))) return json(res, 200, { ad: null, notDue: true, back });
|
||||
const ad = await loginAdFor(req, 'dashboard');
|
||||
if (ad && lk) await loginClock.served(lk);
|
||||
return json(res, 200, { ad, back });
|
||||
|
||||
Reference in New Issue
Block a user