Merge network sign-in (InstantAdPay <-> LinkSpin) into main for the Friday launch (Marty 2026-11-13: 'we need to get that done now'). Conflicts only in script version tags (kept today's newer assets, re-tagged ?v=20261113sso). networksso.test 'ALL PASSED' both repos, networksso.e2e ALL PASSED, iap-qa member ALL PASSED. NETWORK_SSO_SECRET set on both Coolify apps. Chatbot KNOWLEDGE_DATE 2026-11-13.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+6
-1
@@ -25,7 +25,7 @@ let DATA_DIR = null;
|
||||
let chain = null;
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
|
||||
const KNOWLEDGE_DATE = '2026-11-12'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
const KNOWLEDGE_DATE = '2026-11-13'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
|
||||
function init(opts) {
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
@@ -39,6 +39,10 @@ function enabled() { return !!key(); }
|
||||
// handoff: true makes the widget offer "Send this to support" under the answer (help desk, 2026-10-16)
|
||||
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at linkspin|someone|a (human|person|real person))|support (email|address|ticket|team|desk|page)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
|
||||
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 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,
|
||||
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.' },
|
||||
{ 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,
|
||||
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.' },
|
||||
@@ -219,6 +223,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).
|
||||
- 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.
|
||||
- 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.
|
||||
- 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:
|
||||
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
|
||||
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
|
||||
//
|
||||
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
||||
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||
// P mints a token bound to R, the state and the email, and sends the browser
|
||||
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
|
||||
// (so nobody can push their own token into someone else's browser), and spends
|
||||
// the nonce (a second use is refused). The email must already be a member
|
||||
// here; then R makes an ordinary session and redirects to the relative path.
|
||||
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||
// bots and non-page fetches never bounce.
|
||||
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||
// st, to, iat, exp, n }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
const TTL = 60 * 1000; // token life
|
||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||
const STATE_AGE = 300; // seconds: the state cookie
|
||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
||||
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||
|
||||
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email), signIn(email, req), landing(to), signinPath(to), defaultPath }
|
||||
|
||||
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
|
||||
|
||||
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
|
||||
function safePath(to, dflt) {
|
||||
const d = dflt == null ? '/' : dflt;
|
||||
const s = String(to == null ? '' : to);
|
||||
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
|
||||
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
|
||||
}
|
||||
|
||||
function mint(o) {
|
||||
const now = o.now || Date.now();
|
||||
const body = b64u(JSON.stringify({ iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') }));
|
||||
return 'v1.' + body + '.' + b64u(mac(body));
|
||||
}
|
||||
|
||||
// -> { ok, email, to, n, exp } or { error: reason }
|
||||
function verify(tok, o) {
|
||||
if (!enabled()) return { error: 'off' };
|
||||
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||
if (!m) return { error: 'malformed' };
|
||||
const want = mac(m[1]), got = unb64u(m[2]);
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||
const now = (o && o.now) || Date.now();
|
||||
if (!p || p.aud !== o.aud || p.iss !== o.iss) return { error: 'audience' };
|
||||
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||
const st = String((o && o.st) || '');
|
||||
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||
return { ok: true, email: String(p.email).toLowerCase(), to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||
}
|
||||
|
||||
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
|
||||
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
|
||||
function loadFile() {
|
||||
if (fileLoaded) return; fileLoaded = true;
|
||||
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
|
||||
}
|
||||
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
|
||||
async function spend(n, exp) {
|
||||
const now = Date.now(); loadFile(); prune(now);
|
||||
if (used.has(n)) return false;
|
||||
used.set(n, Number(exp) + SKEW); saveFile();
|
||||
const db = C && C.db;
|
||||
if (db && db.enabled && db.enabled()) {
|
||||
try {
|
||||
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
|
||||
await tableReady;
|
||||
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
|
||||
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
|
||||
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// crawlers, link previews and headless browsers never bounce
|
||||
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
|
||||
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
|
||||
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
|
||||
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
|
||||
|
||||
function cookies(req) {
|
||||
const out = {};
|
||||
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||
return out;
|
||||
}
|
||||
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
|
||||
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||
|
||||
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
|
||||
|
||||
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
|
||||
// -> true when the request was one of ours and has been answered
|
||||
async function handle(req, res, u) {
|
||||
if (!C || req.method !== 'GET') return false;
|
||||
const p = u.pathname;
|
||||
const peerName = NAMES[C.peer] || C.peer;
|
||||
if (p === '/go/' + C.peer) {
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const plain = C.peerBase() + to;
|
||||
if (!enabled() || isBot(req)) return go(res, plain);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) return go(res, plain);
|
||||
return go(res, C.peerBase() + '/sso/start?mode=go&to=' + encodeURIComponent(to));
|
||||
}
|
||||
if (p === '/sso/start') {
|
||||
const to = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (s && s.email) return go(res, to); // already signed in here
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const set = [ck('nsso.st', st, STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, C.peerBase() + '/sso/check?st=' + st + '&to=' + encodeURIComponent(to), set);
|
||||
}
|
||||
if (p === '/sso/check') {
|
||||
const st = String(u.searchParams.get('st') || '');
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const none = C.peerBase() + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) { log('check: not signed in here', null, 'for ' + peerName); return go(res, none); }
|
||||
log('token issued', s.email, 'for ' + peerName);
|
||||
return go(res, C.peerBase() + '/sso/in?t=' + mint({ iss: C.self, aud: C.peer, email: s.email, st, to }));
|
||||
}
|
||||
if (p === '/sso/in') {
|
||||
const c = cookies(req);
|
||||
const set = [ck('nsso.st', '', 0, true)];
|
||||
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
||||
const v = verify(u.searchParams.get('t'), { iss: C.peer, 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); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
|
||||
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
|
||||
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
|
||||
return go(res, C.signinPath(v.to), set);
|
||||
}
|
||||
let cookie = null; try { cookie = await C.signIn(v.email, req); } 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 ' + peerName, v.email);
|
||||
return go(res, C.landing(v.to), set);
|
||||
}
|
||||
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);
|
||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||
return sendJson(res, out, set);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = { init, handle, enabled, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
+4
-4
@@ -75,9 +75,9 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/ads-screen.js?v=20261112txt"></script>
|
||||
<script src="/assets/fuel.js?v=20261025ff"></script>
|
||||
<script src="/assets/engine-room.js?v=20261101t"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261113sso"></script>
|
||||
<script src="/assets/ads-screen.js?v=20261113sso"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script>
|
||||
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
// <div id="page">, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
|
||||
window.CR = (function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
// network sign-in (2026-11-12): signed in on InstantAdPay = signed in here, no code (netsso.js asks the server once; same file on both sites)
|
||||
try { if (!document.querySelector('script[src^="/assets/netsso.js"]')) { const ns = document.createElement('script'); ns.src = '/assets/netsso.js?v=20261112sso'; ns.async = true; document.head.appendChild(ns); } } catch (e) {}
|
||||
// launch day is 2026-11-15 Central: the pre-launch notice shows only before it
|
||||
function prelaunch() { try { return new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) < '2026-11-15'; } catch (e) { return false; } }
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
@@ -66,7 +68,7 @@ window.CR = (function () {
|
||||
if (!ARR || $('crArrive')) return '';
|
||||
if (!document.getElementById('crArriveCss')) { const st = document.createElement('style'); st.id = 'crArriveCss'; st.textContent = '.arrive{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:12px 24px 0;padding:10px 14px;border:1px solid var(--sig,#ff6a1a);border-radius:8px;background:var(--sig-soft,#FFF8F2);font-size:13.5px;line-height:1.45}.arrive .grow{flex:1 1 auto}.arrive button{border:0;background:none;font-size:18px;line-height:1;cursor:pointer;color:inherit;padding:0 2px}@media (max-width:900px){.arrive{margin:10px 16px 0}}.cr-flash{animation:crFlash 2.4s ease-out 1}@keyframes crFlash{0%,40%{box-shadow:0 0 0 4px rgba(255,106,26,.55)}100%{box-shadow:0 0 0 0 rgba(255,106,26,0)}}'; document.head.appendChild(st); }
|
||||
return '<div class="arrive" id="crArrive" role="note"><span><b>You came from InstantAdPay to ' + esc(ARR[0]) + '.</b> <span id="crArriveSi">Sign in with the same email you use on InstantAdPay, then </span><b>Step 1:</b> ' + esc(ARR[1])
|
||||
+ (ARR[2] ? ' <a href="' + ARR[2] + '" target="_blank" rel="noopener">' + esc(ARR[3]) + '</a>' : '') + '</span><span class="grow"></span><a href="https://instantadpay.com/my#engine">Back to InstantAdPay</a><button type="button" aria-label="Hide this note" id="crArriveX">×</button></div>';
|
||||
+ (ARR[2] ? ' <a href="' + ARR[2] + '" target="_blank" rel="noopener">' + esc(ARR[3]) + '</a>' : '') + '</span><span class="grow"></span><a href="/go/iap?to=%2Fmy%23engine">Back to InstantAdPay</a><button type="button" aria-label="Hide this note" id="crArriveX">×</button></div>';
|
||||
}
|
||||
// Expired session (Marty 2026-10-23: "told me to sign in but never redirected me"): sessions last 24 h, and a screen
|
||||
// left open past that got 'Sign in first.' errors with no way forward. Any 401 from our API, or coming back to a tab
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
||||
let FROM = 'iap';
|
||||
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return u.href; } catch (e) { return url; } };
|
||||
// a link to the other site goes through this site's /go/<other> hop (network sign-in, 2026-11-12): the member arrives signed in
|
||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return '/go/' + (FROM === 'iap' ? 'linkspin' : 'iap') + '?to=' + encodeURIComponent(u.pathname + u.search + u.hash); } catch (e) { return url; } };
|
||||
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
||||
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
||||
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
: '<p style="margin:0 0 8px">Next refuel day <b>' + esc(v.refuelDayLabel) + '</b> (Central). Window opens ' + esc(v.opensLabel) + ', grace to ' + esc(v.graceLabel) + '.</p>';
|
||||
if (c.month) h += '<div style="margin:0 0 8px">' + site('InstantAdPay', c.iap, v.minUsd.iap) + site('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</div>';
|
||||
if (!v.windowOpen && c.month && !c.both) h += '<p class="muted" style="margin:0 0 8px">Refuel ' + (c.linkspin && c.linkspin.refueled ? 'InstantAdPay ($' + v.minUsd.iap + '+)' : 'LinkSpin ($' + v.minUsd.linkspin + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to +' + v.next.secondEngine + '%.'
|
||||
+ (c.linkspin && c.linkspin.refueled ? ' <a href="https://instantadpay.com/my#buy" target="_blank" rel="noopener">Buy on InstantAdPay ↗</a>' : '') + '</p>';
|
||||
+ (c.linkspin && c.linkspin.refueled ? ' <a href="/go/iap?to=%2Fmy%23buy" target="_blank" rel="noopener">Buy on InstantAdPay ↗</a>' : '') + '</p>';
|
||||
if (v.pitStop && (v.pitStop.linkspin || v.pitStop.usedLinkspin)) h += '<p class="muted" style="margin:0 0 8px"><b>Pit Stop</b> ' + (v.pitStop.linkspin ? 'available here: +' + v.pitStop.pct + '% on a $' + v.minUsd.linkspin + '+ top-up, once this cycle. It does not count as your refuel.' : 'used here this cycle.') + '</p>';
|
||||
h += '<p class="muted" style="margin:0 0 10px">' + (v.freeMiss.available ? 'One free miss left this year.' : 'Free miss for this year used.') + '</p>';
|
||||
const lsDone = c.linkspin && c.linkspin.refueled;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Network sign-in, the sign-in page side (2026-11-12). The SAME file ships in InstantAdPay and LinkSpin (see networksso.js).
|
||||
// On a sign-in screen with no session: ask /api/sso/status once; { check: true } means bounce once through the other site,
|
||||
// which signs the member in here if they are signed in there (the server allows one try per browser per 30 minutes and none
|
||||
// after a sign-out). { hint } means they came from the other site but need the email code here the first time: fill it in.
|
||||
(function () {
|
||||
if (window.__netsso) return; window.__netsso = 1;
|
||||
const BOXES = '#mcEmail,#jnEmail,#siEmail';
|
||||
function fill(email, peer) {
|
||||
let n = 0;
|
||||
const t = setInterval(() => {
|
||||
const el = document.querySelector(BOXES);
|
||||
if (el && el.offsetParent !== null) {
|
||||
clearInterval(t);
|
||||
if (!el.value) el.value = email;
|
||||
if (!document.getElementById('nssoNote')) {
|
||||
const p = document.createElement('p'); p.id = 'nssoNote'; p.className = 'muted small'; p.setAttribute('role', 'note'); p.style.margin = '6px 0';
|
||||
p.textContent = 'Welcome over from ' + peer + '. The first time here, send yourself a code with the same email to finish signing in. After that, ' + peer + ' signs you in here.';
|
||||
(el.closest('label') || el).insertAdjacentElement('afterend', p);
|
||||
}
|
||||
try { el.focus(); } catch (e) {}
|
||||
} else if (++n > 60) clearInterval(t);
|
||||
}, 250);
|
||||
}
|
||||
fetch('/api/sso/status', { credentials: 'same-origin', headers: { Accept: 'application/json' }, cache: 'no-store' })
|
||||
.then(r => r.json()).then(d => {
|
||||
if (!d) return;
|
||||
if (d.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search + location.hash)); return; }
|
||||
if (d.hint) fill(String(d.hint), String(d.peer || 'the other site'));
|
||||
}).catch(() => {});
|
||||
})();
|
||||
@@ -70,7 +70,7 @@
|
||||
<div id="goalReports"></div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/conversions.js?v=20261026a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-2
@@ -83,8 +83,8 @@
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261107tg"></script>
|
||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/credits-screen.js?v=20261107tg"></script>
|
||||
<script src="/assets/fuel.js?v=20261025ff"></script>
|
||||
<script src="/assets/fuel.js?v=20261112sso"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@
|
||||
<div id="page">
|
||||
<div class="body" id="helpBody"><div class="panel"><span class="muted">loading</span></div></div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/help-screen.js?v=20261016a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -270,7 +270,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/links.js?v=20261111big"></script>
|
||||
<script src="/assets/banner-spin.js?v=20261105sz"></script>
|
||||
</body>
|
||||
|
||||
+1
-1
@@ -1016,7 +1016,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261107tg"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/tools.js?v=20261011a"></script>
|
||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||
<script src="/assets/promo.js?v=20261020bs3"></script>
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/pages-screen.js?v=20261021t"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/reports.js?v=20261107nc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -128,7 +128,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
||||
<script src="/assets/sources-screen.js?v=20261028a"></script>
|
||||
</body>
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/team.js?v=20261105fd"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
<div class="rules" id="rules"></div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/traffic-guide-data.js?v=20261028a"></script>
|
||||
<script src="/assets/traffic-guide.js?v=20261029b"></script>
|
||||
</body>
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/wallet-screen.js?v=20261023ov"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261111tank"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261112sso"></script>
|
||||
<script src="/assets/zones-screen.js?v=20261010a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12) end to end: boots BOTH servers locally on throwaway DATA_DIRs and drives
|
||||
// a real browser across them. Same file in both repos. node qa/networksso.e2e.mjs
|
||||
// The other repo is found at NSSO_PEER_DIR, else ../../linkspin/site or ../../onchain-ad-membership/site from this site dir.
|
||||
// InstantAdPay runs on http://127.0.0.1:<port> and LinkSpin on http://localhost:<port>: two hosts, so the two sites' cookies
|
||||
// stay apart like instantadpay.com and linkspin.app do. No mail key on either copy (no email can leave), JSON stores, devCode.
|
||||
// Proves: IAP -> LinkSpin and LinkSpin -> IAP arrive signed in without a code; the silent check on a sign-in page (signed in on
|
||||
// the other site -> in; not -> the normal sign-in, one bounce only); signed out on the other site -> normal sign-in; a replayed or
|
||||
// expired token is refused; an email not on the receiving site yet gets the email-code form prefilled, nothing created; sign-out
|
||||
// stays per site; bots never bounce; no email-code request is made by any network sign-in.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const HERE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const HERE_IS_IAP = fs.existsSync(path.join(HERE, 'lssync.js'));
|
||||
const peerGuess = [process.env.NSSO_PEER_DIR, path.resolve(HERE, HERE_IS_IAP ? '../../linkspin/site' : '../../onchain-ad-membership/site')].filter(Boolean);
|
||||
const PEER = peerGuess.find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
const IAP_DIR = HERE_IS_IAP ? HERE : PEER, LS_DIR = HERE_IS_IAP ? PEER : HERE;
|
||||
if (!PEER || !fs.existsSync(path.join(IAP_DIR, 'networksso.js')) || !fs.existsSync(path.join(LS_DIR, 'networksso.js'))) {
|
||||
console.log('SKIP network sign-in e2e: the other repo (with networksso.js) was not found. Set NSSO_PEER_DIR.'); process.exit(0);
|
||||
}
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
const SECRET = crypto.randomBytes(24).toString('hex');
|
||||
const IP = Number(process.env.NSSO_IAP_PORT || 8821), LP = Number(process.env.NSSO_LS_PORT || 8822);
|
||||
const IAP = 'http://127.0.0.1:' + IP, LS = 'http://localhost:' + LP;
|
||||
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
|
||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-e2e-'));
|
||||
// a request log on each server (method + path only), so "no email-code request was made" is checked on the server side
|
||||
const SPY = path.join(TMP, 'reqlog.cjs');
|
||||
fs.writeFileSync(SPY, "const http=require('http');const e=http.Server.prototype.emit;http.Server.prototype.emit=function(ev,req){if(ev==='request'&&req&&req.url)process.stdout.write('REQ '+req.method+' '+String(req.url).split('?')[0]+'\\n');return e.apply(this,arguments);};\n");
|
||||
const logs = { iap: '', ls: '' };
|
||||
function boot(name, dir, port, extra) {
|
||||
const data = path.join(TMP, name); fs.mkdirSync(path.join(data, 'uploads'), { recursive: true });
|
||||
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: data, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: 'localtest', DEV_POL_USD: '0.10',
|
||||
NETWORK_SSO_SECRET: SECRET, SENDGRID_KEY: '', OUTBOUND: '', DATABASE_URL: '', LS_SYNC_SECRET: '', NODE_OPTIONS: '--require ' + JSON.stringify(SPY).slice(1, -1) }, extra);
|
||||
const p = spawn(process.execPath, ['server.js'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env });
|
||||
p.stdout.on('data', d => logs[name] += d); p.stderr.on('data', d => logs[name] += d); return p;
|
||||
}
|
||||
const srvI = boot('iap', IAP_DIR, IP, { LS_URL: LS });
|
||||
const srvL = boot('ls', LS_DIR, LP, { IAP_URL: IAP });
|
||||
const reqs = name => logs[name].split('\n').filter(l => l.startsWith('REQ '));
|
||||
const codeReqs = () => reqs('iap').concat(reqs('ls')).filter(l => /\/api\/auth\/email\/(start|verify)$/.test(l)).length;
|
||||
|
||||
// sign in through the email code over plain HTTP (a separate client: its own IP via x-forwarded-for, its own device)
|
||||
let ipN = 10;
|
||||
async function codeSignIn(base, email) {
|
||||
const h = { 'Content-Type': 'application/json', 'x-forwarded-for': '10.9.0.' + (ipN++), 'User-Agent': UA };
|
||||
const s = await fetch(base + '/api/auth/email/start', { method: 'POST', headers: h, body: JSON.stringify({ email, fts: Date.now() - 5000, fage: 5000 }) }); const sj = await s.json();
|
||||
const dev = (s.headers.getSetCookie ? s.headers.getSetCookie() : []).map(c => c.split(';')[0]).join('; ');
|
||||
const v = await fetch(base + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({}, h, dev ? { Cookie: dev } : {}), body: JSON.stringify({ email, code: sj.devCode }) });
|
||||
const sid = (v.headers.getSetCookie ? v.headers.getSetCookie() : []).map(c => c.split(';')[0]).find(c => c.startsWith('iap.sid='));
|
||||
if (!sid) throw new Error('code sign-in failed on ' + base + ' for ' + email + ': ' + JSON.stringify(sj) + ' / ' + v.status + ' ' + (await v.text()).slice(0, 200));
|
||||
return sid.slice('iap.sid='.length);
|
||||
}
|
||||
const meOf = async (ctx, base) => { const r = await ctx.request.get(base + '/api/me', { headers: { Accept: 'application/json' } }); try { return await r.json(); } catch (e) { return {}; } };
|
||||
async function newCtx(sessions) {
|
||||
const ctx = await browser.newContext({ userAgent: UA });
|
||||
const add = [];
|
||||
if (sessions && sessions.iap) add.push({ name: 'iap.sid', value: sessions.iap, domain: '127.0.0.1', path: '/' });
|
||||
if (sessions && sessions.ls) add.push({ name: 'iap.sid', value: sessions.ls, domain: 'localhost', path: '/' });
|
||||
if (add.length) await ctx.addCookies(add);
|
||||
return ctx;
|
||||
}
|
||||
let browser = null;
|
||||
try {
|
||||
for (let i = 0; i < 60; i++) { let a = false, b = false; try { a = (await fetch(IAP + '/api/config')).ok; } catch (e) {} try { b = (await fetch(LS + '/api/config')).ok; } catch (e) {} if (a && b) break; await sleep(500); }
|
||||
browser = await chromium.launch();
|
||||
// members: A and B have accounts on both sites, C only on InstantAdPay, D only on LinkSpin
|
||||
const A = 'nsso-a@example.com', B = 'nsso-b@example.com', C = 'nsso-c@example.com', D = 'nsso-d@example.com';
|
||||
const aI = await codeSignIn(IAP, A); await codeSignIn(LS, A);
|
||||
const bL = await codeSignIn(LS, B); await codeSignIn(IAP, B);
|
||||
const cI = await codeSignIn(IAP, C);
|
||||
const dL = await codeSignIn(LS, D);
|
||||
const codes0 = codeReqs();
|
||||
|
||||
// 1. IAP -> LinkSpin through the /go hop
|
||||
let ctx = await newCtx({ iap: aI }); let page = await ctx.newPage();
|
||||
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/ads'));
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
let me = await meOf(ctx, LS);
|
||||
ok(page.url() === LS + '/ads' && me.signedIn && me.email === A, 'IAP -> LinkSpin: lands on /ads signed in as the same member, no code', page.url() + ' ' + JSON.stringify({ s: me.signedIn, e: me.email }));
|
||||
ok((await meOf(ctx, IAP)).email === A, 'IAP session untouched');
|
||||
// sign-out on LinkSpin stays on LinkSpin, and the silent check does not sign them straight back in
|
||||
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await page.goto(LS + '/ads'); await page.waitForTimeout(2500);
|
||||
me = await meOf(ctx, LS);
|
||||
ok(!me.signedIn && page.url() === LS + '/ads', 'signed out on LinkSpin: stays signed out there (no automatic sign-in back)', page.url());
|
||||
ok((await meOf(ctx, IAP)).email === A, 'signing out of LinkSpin leaves InstantAdPay signed in');
|
||||
// a deliberate link from IAP still signs them in after the sign-out
|
||||
await page.goto(IAP + '/go/linkspin?to=' + encodeURIComponent('/credits?from=iap&task=refuel#refuel')); await page.waitForLoadState('domcontentloaded');
|
||||
me = await meOf(ctx, LS);
|
||||
ok(me.email === A && page.url() === LS + '/credits?from=iap&task=refuel#refuel', 'after a sign-out, a link from InstantAdPay signs in again and keeps the query and hash', page.url());
|
||||
await ctx.close();
|
||||
|
||||
// 2. LinkSpin -> IAP through the /go hop (dashboard gets ?welcome=1, the step a code sign-in takes for the login ad)
|
||||
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||
const navs = []; page.on('framenavigated', f => { if (f === page.mainFrame()) navs.push(f.url()); });
|
||||
await page.goto(LS + '/go/iap?to=' + encodeURIComponent('/my#engine')); await page.waitForLoadState('domcontentloaded');
|
||||
me = await meOf(ctx, IAP);
|
||||
ok(me.signedIn && me.email === B && navs.some(u => u.startsWith(IAP + '/my?welcome=1#engine')), 'LinkSpin -> IAP: lands on /my#engine signed in as the same member, no code', navs.slice(-2).join(' , '));
|
||||
await ctx.close();
|
||||
|
||||
// 3. silent check: signed in on IAP, open a LinkSpin screen directly
|
||||
ctx = await newCtx({ iap: aI }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/links'); await page.waitForURL(u => String(u).startsWith(LS + '/links'), { timeout: 15000 }); await page.waitForTimeout(2500);
|
||||
me = await meOf(ctx, LS);
|
||||
ok(me.email === A && page.url() === LS + '/links', 'silent check: a LinkSpin screen opened directly signs in through IAP', page.url());
|
||||
await ctx.close();
|
||||
// and the other way: signed in on LinkSpin, open the IAP dashboard
|
||||
ctx = await newCtx({ ls: bL }); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/my'); await page.waitForTimeout(4000);
|
||||
me = await meOf(ctx, IAP);
|
||||
ok(me.email === B && page.url().startsWith(IAP + '/my'), 'silent check: the IAP sign-in page signs in through LinkSpin', page.url());
|
||||
await ctx.close();
|
||||
|
||||
// 4. silent check, signed in nowhere: one bounce, then the normal sign-in; no second bounce on reload
|
||||
ctx = await newCtx(); page = await ctx.newPage();
|
||||
const starts = []; page.on('request', r => { if (r.url().includes('/sso/start')) starts.push(r.url()); });
|
||||
await page.goto(LS + '/ads'); await page.waitForTimeout(3000);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads' && starts.length === 1, 'signed in nowhere: one bounce, back on the page signed out', starts.length + ' bounce(s), ' + page.url());
|
||||
ok(await page.locator('#siEmail').isVisible(), 'the normal email-code sign-in shows');
|
||||
await page.reload(); await page.waitForTimeout(2500);
|
||||
ok(starts.length === 1, 'reload inside 30 minutes: no second bounce (loop guard)', starts.length + ' bounce(s)');
|
||||
await page.goto(IAP + '/my'); await page.waitForTimeout(3000);
|
||||
ok(!(await meOf(ctx, IAP)).signedIn && starts.length === 2 && (await page.locator('#mcEmail').count()) === 1, 'IAP /my signed in nowhere: one bounce, then the normal sign-in', starts.length + ' bounce(s), ' + page.url());
|
||||
await ctx.close();
|
||||
|
||||
// 5. expired / absent session on the provider: signed out on IAP, the /go link is a plain link and LinkSpin asks for the code
|
||||
const aI2 = await codeSignIn(IAP, A);
|
||||
ctx = await newCtx({ iap: aI2 }); page = await ctx.newPage();
|
||||
await ctx.request.post(IAP + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForTimeout(2500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'signed out on IAP: /go/linkspin is a plain link, LinkSpin shows its sign-in', page.url());
|
||||
await ctx.close();
|
||||
// a session that expired on the provider: the check answers none
|
||||
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/sso/start?mode=go&to=%2Fads'); await page.waitForTimeout(1500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'an expired IAP session: the check answers none, normal sign-in');
|
||||
await ctx.close();
|
||||
|
||||
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
||||
ctx = await newCtx({ iap: cI }); page = await ctx.newPage();
|
||||
await page.goto(IAP + '/go/linkspin?to=%2Fads'); await page.waitForSelector('#siEmail', { timeout: 10000 }); await page.waitForTimeout(1500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && (await page.inputValue('#siEmail')) === C && (await page.locator('#nssoNote').count()) === 1, 'IAP member not on LinkSpin yet: LinkSpin sign-in with the email filled in, nothing signed', await page.inputValue('#siEmail'));
|
||||
ok(!fs.readFileSync(path.join(TMP, 'ls', 'accounts.json'), 'utf8').includes(C), 'no LinkSpin account was created by the network sign-in');
|
||||
await ctx.close();
|
||||
ctx = await newCtx({ ls: dL }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/go/iap?to=%2Fmy'); await page.waitForTimeout(4000);
|
||||
ok(!(await meOf(ctx, IAP)).signedIn && page.url().startsWith(IAP + '/my') && (await page.inputValue('#mcEmail').catch(() => '')) === D, 'LinkSpin member not on IAP yet: IAP sign-in with the email filled in, nothing signed', page.url() + ' ' + (await page.inputValue('#mcEmail').catch(() => '?')));
|
||||
await ctx.close();
|
||||
|
||||
// 7. replay: walk the hops by hand, spend the token once, then try it again with the state cookie put back
|
||||
const aI3 = await codeSignIn(IAP, A);
|
||||
ctx = await newCtx({ iap: aI3 });
|
||||
const hop = async url => { const r = await ctx.request.get(url, { maxRedirects: 0, headers: { 'User-Agent': UA, 'sec-fetch-dest': 'document' } }); return r.headers()['location'] || ''; };
|
||||
let loc = await hop(LS + '/sso/start?mode=go&to=%2Fads');
|
||||
const st = (await ctx.cookies(LS)).find(c => c.name === 'nsso.st');
|
||||
loc = await hop(loc.startsWith('http') ? loc : LS + loc);
|
||||
ok(/^http:\/\/localhost:\d+\/sso\/in\?t=v1\./.test(loc), 'provider minted a token for LinkSpin', loc.slice(0, 60));
|
||||
const tokUrl = loc;
|
||||
let land = await hop(tokUrl);
|
||||
ok(land === '/ads' && (await meOf(ctx, LS)).email === A, 'first use signs in');
|
||||
await ctx.request.post(LS + '/api/auth/logout', { headers: { 'Content-Type': 'application/json' }, data: {} });
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st.value, domain: 'localhost', path: '/' }]);
|
||||
land = await hop(tokUrl);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /token already used/.test(logs.ls), 'the same token again is refused (replay), even with the state cookie put back', land);
|
||||
// a token from a different browser (state cookie missing) is refused: login CSRF
|
||||
const ctx2 = await newCtx({ iap: aI3 });
|
||||
const r2 = await ctx2.request.get(LS + '/sso/start?mode=go&to=%2Fads', { maxRedirects: 0, headers: { 'sec-fetch-dest': 'document' } });
|
||||
const l2 = await ctx2.request.get(r2.headers()['location'], { maxRedirects: 0 });
|
||||
const other = await newCtx(); const r3 = await other.request.get(l2.headers()['location'], { maxRedirects: 0 });
|
||||
ok(!(await meOf(other, LS)).signedIn && /refused: state/.test(logs.ls), 'a token opened in another browser (no matching state) is refused', r3.headers()['location']);
|
||||
await ctx2.close(); await other.close();
|
||||
// an expired token (minted by hand with a past clock) is refused
|
||||
const require = createRequire(import.meta.url); process.env.NETWORK_SSO_SECRET = SECRET;
|
||||
const N = require(path.join(IAP_DIR, 'networksso.js'));
|
||||
const st2 = crypto.randomBytes(16).toString('hex');
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]);
|
||||
const old = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads', now: Date.now() - 120000 });
|
||||
await hop(LS + '/sso/in?t=' + old);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: expired/.test(logs.ls), 'an expired token is refused');
|
||||
const forged = N.mint({ iss: 'iap', aud: 'linkspin', email: A, st: st2, to: '/ads' }).replace(/.$/, c => c === 'A' ? 'B' : 'A');
|
||||
await ctx.addCookies([{ name: 'nsso.st', value: st2, domain: 'localhost', path: '/' }]); await hop(LS + '/sso/in?t=' + forged);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && /refused: signature/.test(logs.ls), 'a tampered token is refused');
|
||||
// open redirect: an off-site path never leaves the site
|
||||
const ev = await hop(IAP + '/go/linkspin?to=' + encodeURIComponent('https://evil.example/x'));
|
||||
ok(ev === LS + '/sso/start?mode=go&to=%2F', '/go with an off-site path stays on the network', ev);
|
||||
const ev2 = await ctx.request.get(LS + '/sso/in?none=1&to=' + encodeURIComponent('//evil.example'), { maxRedirects: 0 });
|
||||
ok(ev2.headers()['location'] === '/ads', '/sso/in never redirects off the site', ev2.headers()['location']);
|
||||
await ctx.close();
|
||||
|
||||
// 8. bots and API calls never bounce
|
||||
const bot = await fetch(LS + '/sso/start?to=%2Fads', { redirect: 'manual', headers: { 'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)' } });
|
||||
ok(bot.headers.get('location') === '/ads' && !(bot.headers.getSetCookie ? bot.headers.getSetCookie() : []).length, 'a crawler on /sso/start goes straight to the page');
|
||||
const bs = await (await fetch(IAP + '/api/sso/status', { headers: { 'User-Agent': 'Googlebot/2.1' } })).json();
|
||||
ok(bs.check === false, 'a crawler is never told to check');
|
||||
|
||||
// 9. no email-code request was made by any network sign-in (only the setup code sign-ins above)
|
||||
const total = codeReqs();
|
||||
ok(total === codes0 + 4, 'no email-code request made by any network sign-in (server request log: only the 2 later setup sign-ins, start + verify each)', 'before ' + codes0 + ', after ' + total);
|
||||
ok(!/sendCode|sendgrid/i.test(logs.iap + logs.ls), 'no mail send attempted on either server');
|
||||
ok(/network-sso signed in from InstantAdPay n\*\*\*@example\.com/.test(logs.ls) && /network-sso signed in from LinkSpin n\*\*\*@example\.com/.test(logs.iap), 'successes logged with the email masked');
|
||||
ok(!logs.iap.includes(SECRET) && !logs.ls.includes(SECRET) && !/nsso-a@example\.com/.test((logs.iap + logs.ls).split('\n').filter(l => l.includes('network-sso')).join('\n')), 'no secret and no full email in the network sign-in log lines');
|
||||
} catch (e) { console.log('FAIL exception', e && e.stack || e); fails++; }
|
||||
finally {
|
||||
try { if (browser) await browser.close(); } catch (e) {}
|
||||
try { srvI.kill(); } catch (e) {} try { srvL.kill(); } catch (e) {}
|
||||
await sleep(500); try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (e) {}
|
||||
}
|
||||
if (fails) { for (const k of ['iap', 'ls']) console.log('--- ' + k + ' log (network-sso / errors)\n' + logs[k].split('\n').filter(l => /network-sso|error|Error/.test(l)).slice(-25).join('\n')); }
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,126 @@
|
||||
// Network sign-in (InstantAdPay <-> LinkSpin, 2026-11-12): unit test of networksso.js. Same file in both repos. node qa/networksso.test.cjs
|
||||
// Token sign/verify, expiry, clock skew, tamper, wrong audience, state binding, replay, the secret switch, open redirects,
|
||||
// bots, and the route handler with fake requests (no server, no network, throwaway DATA_DIR).
|
||||
'use strict';
|
||||
const fs = require('fs'), os = require('os'), path = require('path'), crypto = require('crypto');
|
||||
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||
const N = require('../networksso.js');
|
||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nsso-unit-'));
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
|
||||
(async () => {
|
||||
const sessions = { 'tok-a': { email: 'a@example.com' } };
|
||||
const accounts = new Set(['a@example.com']);
|
||||
const signedIn = [];
|
||||
N.init({ self: 'iap', peer: 'linkspin', peerBase: () => 'https://ls.example', isProd: true, dataDir: DATA, db: null, defaultPath: '/my',
|
||||
member: async req => sessions[(/sid=([^;]+)/.exec(req.headers.cookie || '') || [])[1]] || null,
|
||||
accept: async e => accounts.has(e) ? { ok: true } : { fallback: 'no account here yet' },
|
||||
signIn: async e => { signedIn.push(e); return 'iap.sid=new; Path=/; HttpOnly'; },
|
||||
landing: to => to, signinPath: to => '/my' });
|
||||
|
||||
// ---- tokens ----
|
||||
const t = N.mint({ iss: 'linkspin', aud: 'iap', email: 'A@Example.com', st, to: '/my#buy' });
|
||||
let v = N.verify(t, { iss: 'linkspin', aud: 'iap', st });
|
||||
ok(v.ok && v.email === 'a@example.com' && v.to === '/my#buy', 'round trip: email (lower-cased) and path come back', JSON.stringify(v));
|
||||
ok(/^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(t), 'token format v1.<payload>.<hmac>');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'linkspin', st }).error === 'audience', 'wrong audience refused');
|
||||
ok(N.verify(t, { iss: 'iap', aud: 'iap', st }).error === 'audience', 'wrong issuer refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 61000 }).error === 'expired', 'expired after 60 s');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st, now: Date.now() + 55000 }).ok, 'still good at 55 s');
|
||||
const fut = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: '/', now: Date.now() + 120000 });
|
||||
ok(N.verify(fut, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'issued too far in the future refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: crypto.randomBytes(16).toString('hex') }).error === 'state', 'state from another browser refused');
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st: '' }).error === 'state', 'missing state cookie refused');
|
||||
const [, body, mac] = t.split('.');
|
||||
const pl = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString()); pl.email = 'evil@example.com';
|
||||
ok(N.verify('v1.' + b64u(JSON.stringify(pl)) + '.' + mac, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'payload tampered (email swapped) refused');
|
||||
ok(N.verify('v1.' + body + '.' + (mac[0] === 'A' ? 'B' : 'A') + mac.slice(1), { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'signature tampered refused');
|
||||
const longer = JSON.parse(JSON.stringify(pl)); longer.email = 'a@example.com'; longer.exp = longer.iat + 3600000;
|
||||
const forged = 'v1.' + b64u(JSON.stringify(longer)) + '.' + b64u(crypto.createHmac('sha256', process.env.NETWORK_SSO_SECRET).update('nsso.v1.' + b64u(JSON.stringify(longer))).digest());
|
||||
ok(N.verify(forged, { iss: 'linkspin', aud: 'iap', st }).error === 'expired', 'a validly signed token with a life over 60 s is refused');
|
||||
ok(N.verify('garbage', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed' && N.verify('', { iss: 'linkspin', aud: 'iap', st }).error === 'malformed', 'garbage refused');
|
||||
process.env.NETWORK_SSO_SECRET = 'w'.repeat(48);
|
||||
ok(N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'signature', 'another secret refused');
|
||||
process.env.NETWORK_SSO_SECRET = 'short';
|
||||
ok(!N.enabled() && N.verify(t, { iss: 'linkspin', aud: 'iap', st }).error === 'off', 'secret under 32 characters = switched off');
|
||||
process.env.NETWORK_SSO_SECRET = 'u'.repeat(48);
|
||||
|
||||
// ---- replay ----
|
||||
ok(await N.spend(v.n, v.exp) === true, 'first use of a nonce is spent');
|
||||
ok(await N.spend(v.n, v.exp) === false, 'second use of the same nonce refused (replay)');
|
||||
ok(JSON.parse(fs.readFileSync(path.join(DATA, 'network-sso-nonces.json'), 'utf8'))[v.n] > 0, 'spent nonce kept on disk (survives a restart inside the window)');
|
||||
|
||||
// ---- open redirects ----
|
||||
const bad = ['https://evil.example/x', '//evil.example/x', '/\\evil.example', '\\\\evil.example', 'javascript:alert(1)', '/x\r\nSet-Cookie: a=b', ' /my', '/my\t', 'http:/evil.example', '/' + 'a'.repeat(700), '', null];
|
||||
ok(bad.every(b => N.safePath(b, '/my') === '/my'), 'off-site, protocol-relative, backslash, script, header-injection and over-long paths fall back to the default', bad.map(b => N.safePath(b, '/my')).filter(x => x !== '/my').join(' | '));
|
||||
ok(N.safePath('/credits?from=iap&task=refuel#refuel') === '/credits?from=iap&task=refuel#refuel' && N.safePath('/my#buy') === '/my#buy', 'same-site paths with query and hash pass');
|
||||
ok(N.safePath('/%2F%2Fevil.example') === '/%2F%2Fevil.example', 'an encoded // stays a path on this site');
|
||||
const t2 = N.mint({ iss: 'linkspin', aud: 'iap', email: 'a@example.com', st, to: 'https://evil.example/' });
|
||||
ok(N.verify(t2, { iss: 'linkspin', aud: 'iap', st }).to === '/', 'a token carrying an off-site path lands on /');
|
||||
|
||||
// ---- bots ----
|
||||
const R = (url, cookie, ua, extra) => ({ method: 'GET', url, headers: Object.assign({ cookie: cookie || '', 'user-agent': ua === undefined ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130 Safari/537.36' : ua }, extra || {}) });
|
||||
ok(N.isBot(R('/', '', 'Googlebot/2.1')) && N.isBot(R('/', '', 'facebookexternalhit/1.1')) && N.isBot(R('/', '', '')) && N.isBot(R('/', '', 'Mozilla/5.0 HeadlessChrome/120')) && !N.isBot(R('/')), 'bots, previews, headless and empty agents are bots; a browser is not');
|
||||
|
||||
// ---- the handler ----
|
||||
const call = async req => { let code = 0, h = {}, body = ''; const res = { writeHead: (c, hh) => { code = c; h = hh || {}; }, end: b => { body = b || ''; } };
|
||||
const handled = await N.handle(req, res, new URL(req.url, 'http://x')); const set = [].concat(h['Set-Cookie'] || []); return { handled, code, loc: h.Location, set, body }; };
|
||||
let r = await call(R('/go/linkspin?to=/ads'));
|
||||
ok(r.code === 302 && r.loc === 'https://ls.example/ads', '/go signed out: a plain link to the other site');
|
||||
r = await call(R('/go/linkspin?to=//evil.example', 'sid=tok-a'));
|
||||
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2F', '/go never forwards an off-site path', r.loc);
|
||||
r = await call(R('/go/linkspin?to=/ads%3Fx%3D1', 'sid=tok-a'));
|
||||
ok(r.loc === 'https://ls.example/sso/start?mode=go&to=%2Fads%3Fx%3D1', '/go signed in: through the other site\'s /sso/start', r.loc);
|
||||
r = await call(R('/sso/start?to=/my', '', 'Googlebot/2.1'));
|
||||
ok(r.loc === '/my' && !r.set.length, 'bot on /sso/start: no bounce, no cookies');
|
||||
r = await call(R('/sso/start?to=/my', '', undefined, { 'sec-fetch-dest': 'empty' }));
|
||||
ok(r.loc === '/my' && !r.set.length, 'a fetch (not a page load) never bounces');
|
||||
r = await call(R('/sso/start?to=/my', 'nsso.tried=1'));
|
||||
ok(r.loc === '/my', 'loop guard: a second silent check inside 30 minutes goes straight to the page');
|
||||
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
||||
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
||||
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
||||
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||
r = await call(R('/sso/start?to=https://evil.example'));
|
||||
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
||||
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
|
||||
r = await call(R('/sso/start?to=/my', 'sid=tok-a'));
|
||||
ok(r.loc === '/my' && !r.set.length, 'already signed in here: no bounce');
|
||||
r = await call(R('/sso/check?st=' + st + '&to=/ads'));
|
||||
ok(r.loc === 'https://ls.example/sso/in?none=1&to=%2Fads', 'provider, signed out: none');
|
||||
r = await call(R('/sso/check?st=nothex&to=/ads', 'sid=tok-a'));
|
||||
ok(r.loc.includes('none=1'), 'provider: a malformed state gets none, never a token');
|
||||
r = await call(R('/sso/check?st=' + st + '&to=/ads', 'sid=tok-a'));
|
||||
const issued = new URL(r.loc).searchParams.get('t');
|
||||
ok(r.loc.startsWith('https://ls.example/sso/in?t=v1.') && N.verify(issued, { iss: 'iap', aud: 'linkspin', st }).email === 'a@example.com', 'provider, signed in: a token for the other site only, bound to the state');
|
||||
// receiver: a LinkSpin-issued token arriving here
|
||||
const mk = (email, to) => N.mint({ iss: 'linkspin', aud: 'iap', email, st, to });
|
||||
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my#buy'), 'nsso.st=' + st));
|
||||
ok(r.loc === '/my#buy' && r.set.includes('iap.sid=new; Path=/; HttpOnly') && signedIn.length === 1, 'receiver: valid token -> session cookie, redirect to the path');
|
||||
const once = mk('a@example.com', '/my');
|
||||
r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st)); r = await call(R('/sso/in?t=' + once, 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2 && !r.set.some(c => c.startsWith('iap.sid=')), 'receiver: the same token twice signs in once (replay refused)');
|
||||
r = await call(R('/sso/in?t=' + mk('a@example.com', '/my'), 'nsso.st=' + crypto.randomBytes(16).toString('hex')));
|
||||
ok(signedIn.length === 2 && r.loc === '/my', 'receiver: a token pushed into another browser (login CSRF) is refused');
|
||||
r = await call(R('/sso/in?t=' + issued, 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2, 'receiver: a token minted FOR the other site is refused here');
|
||||
r = await call(R('/sso/in?t=' + mk('new@example.com', '/my'), 'nsso.st=' + st));
|
||||
ok(signedIn.length === 2 && r.loc === '/my' && r.set.some(c => /^nsso\.hint=new%40example\.com;.*HttpOnly/.test(c)), 'receiver: not a member here yet -> normal sign-in with the email kept for the form, nothing created');
|
||||
r = await call(R('/sso/in?none=1&to=https://evil.example', 'nsso.st=' + st));
|
||||
ok(r.loc === '/my' && r.set.some(c => /^nsso\.st=;/.test(c)), 'receiver: none -> the sign-in page, never an off-site path');
|
||||
r = await call(R('/api/sso/status', 'nsso.hint=new%40example.com; nsso.tried=1'));
|
||||
let j = JSON.parse(r.body); ok(j.hint === 'new@example.com' && j.check === false && r.set.some(c => /^nsso\.hint=;/.test(c)), '/api/sso/status hands the hint over once and clears it');
|
||||
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === true && j.peer === 'LinkSpin', '/api/sso/status: signed out, fresh browser -> check');
|
||||
j = JSON.parse((await call(R('/api/sso/status', 'sid=tok-a'))).body); ok(j.check === false, '/api/sso/status: signed in -> no check');
|
||||
j = JSON.parse((await call(R('/api/sso/status', '', 'Googlebot/2.1'))).body); ok(j.check === false, '/api/sso/status: bot -> no check');
|
||||
process.env.NETWORK_SSO_SECRET = '';
|
||||
r = await call(R('/go/linkspin?to=/ads', 'sid=tok-a')); ok(r.loc === 'https://ls.example/ads', 'secret not set: /go is a plain link');
|
||||
j = JSON.parse((await call(R('/api/sso/status'))).body); ok(j.check === false, 'secret not set: no silent check');
|
||||
ok(N.offCookie().startsWith('nsso.off=1;') && /Max-Age=43200/.test(N.offCookie()), 'sign-out cookie pauses the silent check 12 hours');
|
||||
ok(!(await call({ method: 'POST', url: '/sso/in', headers: {} })).handled, 'non-GET requests are not handled');
|
||||
})().catch(e => { console.log('FAIL exception', e && e.stack || e); fails++; }).finally(() => {
|
||||
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exitCode = fails ? 1 : 0;
|
||||
});
|
||||
@@ -2,6 +2,7 @@
|
||||
# InstantAdPay QA harness runner. From the site dir:
|
||||
# bash qa/run.sh public # live public pages only (no local server)
|
||||
# bash qa/run.sh member # local copy: member + admin walk
|
||||
# bash qa/run.sh sso # network sign-in InstantAdPay <-> LinkSpin: unit + both servers end to end (NSSO_PEER_DIR = the other repo's site dir if not side by side; also runs in member)
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
@@ -64,8 +65,13 @@ elif [ "$MODE" = "override" ]; then
|
||||
node qa/override.test.cjs || status=1
|
||||
elif [ "$MODE" = "launchweek" ]; then
|
||||
node qa/launchweek.test.cjs || status=1
|
||||
elif [ "$MODE" = "sso" ]; then
|
||||
node qa/networksso.test.cjs || status=1
|
||||
node qa/networksso.e2e.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||
node qa/tank-hold.test.mjs || status=1
|
||||
node qa/profile-policy.test.cjs || status=1
|
||||
node qa/netconv.test.mjs || status=1
|
||||
|
||||
@@ -15,6 +15,7 @@ const { URL } = require('url');
|
||||
const chain = require('./chain');
|
||||
const auth = require('./auth');
|
||||
const accounts = require('./accounts');
|
||||
const networksso = require('./networksso'); // network sign-in with InstantAdPay (2026-11-12, Marty approved): see networksso.js
|
||||
const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages
|
||||
const ads = require('./ads');
|
||||
const mailer = require('./mailer');
|
||||
@@ -632,6 +633,24 @@ async function boot() {
|
||||
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {});
|
||||
if (ev && ev.type === 'Purchase') refuel.onPurchase(ev).catch(e => console.error('refuel report', e.message)); } }); // no-op while refuelStreak is off
|
||||
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
|
||||
// network sign-in (2026-11-12): a member signed in on InstantAdPay arrives here signed in, and the other way round. Member
|
||||
// sessions only (the admin portal is never shared). An email that is not here yet (the 2-minute sync has not run) or is not
|
||||
// let in (LS_TESTERS) gets the normal email-code sign-in with the email filled in; nothing is created by the network sign-in.
|
||||
networksso.init({ self: 'linkspin', peer: 'iap', peerBase: IAP_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/ads',
|
||||
member: async req => { const s = await auth.fromRequest(req); return s && s.email ? s : null; },
|
||||
accept: async email => {
|
||||
const a = await accounts.byEmail(email);
|
||||
if (!a) return { fallback: 'no account here yet' };
|
||||
if (!isTester(email, a)) return { fallback: 'not on the tester list' };
|
||||
return { ok: true };
|
||||
},
|
||||
signIn: async email => { // the same session the email code makes (4 hours, same rights)
|
||||
const a = await accounts.byEmail(email); let memberId = 0;
|
||||
if (a && a.address) { try { memberId = await chain.memberIdByAccount(a.address); } catch (e) {} }
|
||||
return auth.sessionCookie(await auth.mintSession({ email: a.email, address: a.address || null, memberId }));
|
||||
},
|
||||
landing: to => to,
|
||||
signinPath: to => (to === '/' ? '/ads' : to) }); // every Control Room screen shows the sign-in itself
|
||||
accounts.init({ dataDir: DATA_DIR });
|
||||
ads.init({ dataDir: DATA_DIR, chain });
|
||||
mailer.init({ dataDir: DATA_DIR });
|
||||
@@ -1397,6 +1416,8 @@ const server = http.createServer(async (req, res) => {
|
||||
const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p === '/t.js' || p === '/t.gif' || p === '/cv.gif' || p === '/cv.js' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-') || /^\/(i|c|s)\/[a-z0-9]{5,12}(\.gif|\.js)?$/.test(p); // + Banner Spin image / click / script (2026-10-18)
|
||||
// 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
|
||||
// network sign-in with InstantAdPay (2026-11-12): /go/iap, /sso/start, /sso/check, /sso/in, /api/sso/status (app host only)
|
||||
if (req.method === 'GET' && (p === '/go/iap' || p.startsWith('/sso/') || p === '/api/sso/status') && !isPagesHost(req) && !isLinkHost(req) && await networksso.handle(req, res, u)) return;
|
||||
|
||||
// -- the rotator redirect: one hop, recorded, on any host (LinkSpin)
|
||||
let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p);
|
||||
@@ -2025,7 +2046,7 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (p === '/api/auth/logout' && req.method === 'POST') {
|
||||
await auth.logout(req);
|
||||
return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() });
|
||||
return json(res, 200, { ok: true }, { 'Set-Cookie': [auth.clearCookie(), networksso.offCookie()] }); // signed out stays signed out: no silent network sign-in here for 12 hours
|
||||
}
|
||||
if (p === '/api/gas' && req.method === 'GET') {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user