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:
@@ -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
|
||||
@@ -61,8 +62,13 @@ syntax_gate
|
||||
if [ "$MODE" = "public" ]; then
|
||||
node qa/walk.mjs public || status=1
|
||||
node qa/chatbot-sync.mjs || 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.mjs || status=1
|
||||
node qa/walletnudge.test.cjs || status=1
|
||||
node qa/bixpay.test.cjs || status=1
|
||||
|
||||
Reference in New Issue
Block a user