Files
HotSpot/backend/test/portal-access.test.js
2026-10-22 22:17:12 +00:00

208 lines
13 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const html=fs.readFileSync(new URL('../public/index.html',import.meta.url),'utf8');
const code=html.match(/<script>([\s\S]*?)<\/script>/)[1];
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true,clipboardAvailable=true,legacyCopy=false,siteConfig={},paymentStatus={status:'pending'}}) {
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
const listeners=new Map(),clipboard=[];
const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',style:{},attributes:{},setAttribute(k,v){this.attributes[k]=v;},removeAttribute(k){delete this.attributes[k];},classList:{toggle(){},add(){},remove(){}},addEventListener:(event,fn)=>listeners.set(id+':'+event,fn),appendChild(){}}]));
const requests=[],forms=[],intervals=[],navigations=[];
const sandbox={URL,URLSearchParams,Date,AbortController,console,location:{search},navigator:{},sessionStorage:{getItem:k=>storage[k]??null,setItem:(k,v)=>storage[k]=v,removeItem:k=>delete storage[k]},document:{getElementById:id=>{assert.ok(elements.has(id),'Missing element '+id);return elements.get(id);},body:{append(){}},createElement:tag=>({append(){},submit(){forms.push(tag);}})},setTimeout(){},clearTimeout(){},setInterval:fn=>{intervals.push(fn);return intervals.length;},clearInterval(){},window:{addEventListener(){},scrollTo(){}}};
sandbox.location.href='https://hotspot.example.test/'+(search || '');
sandbox.window.location={replace:url=>navigations.push(url)};
sandbox.navigator.clipboard={writeText:async text=>{if(!clipboardAvailable)throw new Error('Clipboard denied');clipboard.push(text);}};
sandbox.document.body.appendChild=()=>{};
sandbox.document.createElement=tag=>({append(){},select(){},remove(){},submit(){forms.push(tag);}});
sandbox.document.execCommand=()=>legacyCopy;
sandbox.fetch=async(path,options)=>{
requests.push({path,options});
if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test',...siteConfig})};
if(path==='/api/plans')return {ok:true,json:async()=>[]};
if(path==='/api/access/start')return {ok:access.ok,status:access.ok?200:429,json:async()=>access};
if(path==='/api/checkout')return {ok:true,json:async()=>({paymentId:'Ptest',orderId:'ORDtest',price:3,planName:'1 Hora',copiaCola:'test-pix',qrCodeBase64:null})};
if(path==='/api/status/Ptest')return {ok:true,json:async()=>paymentStatus};
if(path==='/api/access/report')return {ok:true,json:async()=>({ok:true})};
if(path.startsWith('https://www.gstatic.com/') || path.startsWith('https://www.apple.com/')) {
// Fetch rejects no-cors requests unless redirect mode is follow, before any network traffic.
if(options.mode==='no-cors' && (options.redirect ?? 'follow')!=='follow')throw new TypeError('Invalid no-cors redirect mode');
if(!externalAvailable)throw new Error('Network unreachable');
return {type:'opaque',ok:false};
}
throw new Error('Unexpected request '+path);
};
vm.runInNewContext(code,sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
return {requests,elements,forms,intervals,navigations,clipboard,click:async id=>{
await listeners.get(id+':click')();
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
},checkout:async()=>{
elements.get('payerName').value='Teste Usuario';elements.get('payerEmail').value='[email protected]';
await vm.runInNewContext('checkout("plano-1h")',sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
}};
}
test('return from hotspot confirms session even with stale freeOk/freeTried browser flags',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',storage:{freeOk:'1',freeTried:'1'}});
const request=p.requests.find(r=>r.path==='/api/access/start');assert.ok(request);
assert.equal(JSON.parse(request.options.body).mac,'AA:BB:CC:DD:EE:11');
assert.match(p.elements.get('freeAccessMessage').textContent,/confirmada: 120 segundos/);
assert.equal(p.forms.length,0);
});
test('direct portal URL without MAC cannot silently claim temporary access',async()=>{
const p=await portal({search:''});
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/tela de entrada/);
});
test('portal reports cooldown failures and offers retry',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:false,error:'Janela encerrada.',retryAfterSeconds:180}});
assert.match(p.elements.get('freeAccessMessage').textContent,/3 minutos/);
assert.ok(p.elements.has('copyBtn'));
});
test('browsing plans does not consume the payment internet window',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11'});
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/Escolha um plano/);
});
test('generating or restoring a PIX leaves it visible without granting internet or navigating',async()=>{
const storage={};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
await p.checkout();
const paths=p.requests.map(r=>r.path);
assert.ok(paths.includes('/api/checkout'));
assert.ok(!paths.includes('/api/access/start'));
assert.equal(p.navigations.length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/Copiar código PIX/);
assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest');
assert.equal(p.elements.get('copiaCola').textContent,'test-pix');
const reloaded=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
assert.equal(reloaded.elements.get('copiaCola').textContent,'test-pix');
assert.ok(reloaded.requests.some(r=>r.path==='/api/status/Ptest'));
assert.ok(!reloaded.requests.some(r=>r.path==='/api/access/start'));
const staleReturn=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',storage});
assert.ok(!staleReturn.requests.some(r=>r.path==='/api/access/start'));
});
test('client probes external services and reports observations without sending its token externally',async()=>{
for(const externalAvailable of [true,false]){
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:true,authenticated:true,seconds:120,probeToken:'secret-probe'},externalAvailable});
const report=p.requests.find(r=>r.path==='/api/access/report');assert.ok(report);
assert.equal(JSON.parse(report.options.body).results.every(r=>r.ok),externalAvailable);
const external=p.requests.filter(r=>r.path.startsWith('https:'));assert.equal(external.length,2);
for(const r of external){
assert.ok(!JSON.stringify(r).includes('secret-probe'));
assert.equal(r.options.mode,'no-cors');
assert.equal(r.options.redirect,'follow');
assert.equal(r.options.credentials,'omit');
}
assert.match(p.elements.get('freeAccessProbe').textContent,externalAvailable?/alcançou/:/não foi possível confirmar/);
}
});
test('unsupported API login falls back to the hotspot form without claiming confirmed access',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:true,authenticated:false,seconds:120,loginUrl:'http://10.10.10.1/login?username=FREE&password=test&dst=https%3A%2F%2Fhotspot.jf.eng.br%2F'}});
assert.equal(p.forms.length,1);
assert.match(p.elements.get('freeAccessMessage').textContent,/ainda não confirmou/);
assert.equal(p.requests.filter(r=>r.path==='/api/access/report').length,0);
});
test('API login navigates once to trigger captive-network revalidation and restores the PIX',async()=>{
const storage={};
const expiresAt=Date.now()+120000;
const access={ok:true,authenticated:true,seconds:120,expiresAt,probeToken:'private-probe'};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage,access});
await p.checkout();
assert.equal(p.navigations.length,0);
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
await p.click('copyBtn');
assert.deepEqual(p.clipboard,['test-pix']);
assert.equal(p.navigations.length,1);
const target=new URL(p.navigations[0]);
assert.equal(target.origin,'https://hotspot.example.test');
assert.equal(target.searchParams.get('mac'),'AA:BB:CC:DD:EE:11');
assert.equal(target.searchParams.get('free'),'1');
assert.equal(target.searchParams.get('access'),String(expiresAt));
assert.ok(!target.href.includes('private-probe'));
assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest');
assert.equal(p.requests.filter(r=>r.path==='/api/access/report').length,0);
const back=await portal({search:target.search,storage,access:{...access,seconds:103,reused:true}});
assert.equal(back.navigations.length,0);
assert.equal(back.elements.get('copiaCola').textContent,'test-pix');
assert.match(back.elements.get('freeAccessMessage').textContent,/103 segundos/);
assert.ok(back.requests.some(r=>r.path==='/api/access/report'));
assert.equal(storage.freeAccessConfirmedUntil,String(expiresAt));
});
test('failed clipboard copy keeps the PIX open without consuming the internet window',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',clipboardAvailable:false});
await p.checkout();
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.equal(p.navigations.length,0);
assert.equal(p.elements.get('copyBtn').disabled,false);
assert.match(p.elements.get('toast').textContent,/copie o código manualmente/);
assert.equal(p.elements.has('retryFreeAccess'),false);
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
});
test('legacy clipboard success permits access only after the copy attempt succeeds',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',clipboardAvailable:false,legacyCopy:true});
await p.checkout();
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
});
test('an expired or denied window cannot navigate, and a new window can revalidate again',async()=>{
const previous=Date.now()-1000;
const storage={freeAccessConfirmedUntil:String(previous)};
const search='?mac=AA:BB:CC:DD:EE:11&free=1';
const expired=await portal({search,storage,access:{ok:true,authenticated:true,seconds:0,expiresAt:previous}});
assert.equal(expired.navigations.length,0);
const denied=await portal({search,storage,access:{ok:false,error:'Aguarde',expiresAt:Date.now()+120000}});
assert.equal(denied.navigations.length,0);
const next=await portal({search,storage,access:{ok:true,authenticated:true,seconds:120,expiresAt:Date.now()+120000}});
assert.equal(next.navigations.length,1);
});
test('guided payment has clear rules and one copy action without a separate release button',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',siteConfig:{freeSeconds:180,freeCooldownSeconds:2700}});
assert.match(p.elements.get('accessRules').textContent,/3 minutos/);
assert.match(p.elements.get('accessRules').textContent,/45 minutos após o fim/);
assert.equal(p.elements.has('retryFreeAccess'),false);
assert.equal(p.elements.has('accessConsent'),false);
await p.checkout();
assert.equal(p.elements.get('step-pay').attributes['aria-current'],'step');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
});
test('privacy information is available outside the steps and never requests a bank password',()=>{
assert.match(html,/<details[^>]*id="privacyNotice"/);
assert.match(html,/Seus dados e sua privacidade \(LGPD\)/);
assert.match(html,/não pede sua senha do banco/);
assert.match(html,/acesso, correção e exclusão quando cabível/);
assert.ok(!html.includes('id="retryFreeAccess"'));
});
test('privacy environment fields render as text, including markup, without replacing HTML',async()=>{
const privacy={controller:'Empresa Exemplo',contact:'[email protected]',retention:'Registros de compra: <b>prazo definido pelo responsável</b>'};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',siteConfig:{privacy}});
assert.equal(p.elements.get('privacyController').textContent,privacy.controller);
assert.equal(p.elements.get('privacyContact').textContent,privacy.contact);
assert.equal(p.elements.get('privacyRetention').textContent,privacy.retention);
assert.equal(p.elements.get('privacyRetention').innerHTML,'');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
});
test('confirmed payment distinguishes activation pending from an active paid connection',async()=>{
for(const state of ['pending','active']){
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage:{paymentId:'Ptest'},paymentStatus:{status:'paid',voucher:{user:'paid-user',pass:'paid-pass'},connection:{state}}});
assert.equal(p.elements.get('vUser').textContent,'paid-user');
assert.match(p.elements.get('paidConnectionMessage').textContent,state==='active'?/plano está ativo/:/Ativando/);
assert.equal(p.elements.get('freeCountdown').textContent,state==='active'?'Conectado':'Ativando');
assert.equal(p.forms.length,0);
}
});