Revalidate captive Wi-Fi with one portal navigation after API login
build-image / build-push (push) Successful in 2m44s

This commit is contained in:
jfeng committed 2026-10-22 17:23:16 +00:00
1 parent 4c7440e233
commit 8d38a9136b
3 files changed
+56 -3

No files matched your search

+3 -1
View File
@@ -1,4 +1,4 @@
# INCTG — Wi-Fi com PIX # INCTG — Wi-Fi com PIX
Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hotspot MikroTik. Backend Node.js 22 + Express; interface HTML/CSS/JavaScript; persistência local em JSON. Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hotspot MikroTik. Backend Node.js 22 + Express; interface HTML/CSS/JavaScript; persistência local em JSON.
@@ -86,6 +86,8 @@ O walled garden e a exceção do firewall para o portal local devem usar a porta
Depois de confirmar a sessão, o portal tenta consultar Google e Apple diretamente do navegador, sem enviar o MAC ou token da janela a esses destinos. Os resultados ficam no registro temporário e nos logs `[ACESSO CLIENTE]`. Esse é um diagnóstico do navegador: bloqueadores, falhas dos destinos ou uso de dados móveis podem interferir. Para validar especificamente o Wi-Fi, teste no aparelho com os dados móveis desligados. Depois de confirmar a sessão, o portal tenta consultar Google e Apple diretamente do navegador, sem enviar o MAC ou token da janela a esses destinos. Os resultados ficam no registro temporário e nos logs `[ACESSO CLIENTE]`. Esse é um diagnóstico do navegador: bloqueadores, falhas dos destinos ou uso de dados móveis podem interferir. Para validar especificamente o Wi-Fi, teste no aparelho com os dados móveis desligados.
Após a autenticação pela API, o portal faz uma navegação automática no próprio domínio uma vez por janela temporária. A tela de entrada de rede do Android reavalia a conectividade ao navegar; apenas atualizar o contador por JavaScript pode deixar o aparelho tratando o Wi-Fi como sem internet. O PIX continua no armazenamento da sessão, e o retorno reutiliza o prazo original do backend, sem renovar os dois minutos. A validação final deste comportamento precisa ser feita no celular, sem desconectar o Wi-Fi.
A API TCP 8728 deve ficar restrita ao IP LAN do backend, com usuário dedicado. A API e o login HTTP-PAP são tráfego sem TLS na LAN; para ambientes não confiáveis, configure API-SSL e hotspot HTTPS antes de adaptar os clientes. Não exponha a API RouterOS na internet. A API TCP 8728 deve ficar restrita ao IP LAN do backend, com usuário dedicado. A API e o login HTTP-PAP são tráfego sem TLS na LAN; para ambientes não confiáveis, configure API-SSL e hotspot HTTPS antes de adaptar os clientes. Não exponha a API RouterOS na internet.
O backend não garante identidade do aparelho a partir de um MAC informado pelo cliente. O acesso temporário é vinculado ao MAC existente no roteador e tem limite/cooldown, mas prevenção completa contra spoofing exige autenticação adicional na rede. A separação entre clientes no mesmo switch exige isolamento de portas/VLAN no equipamento; firewall IP não isola tráfego de camada 2. IPv6 dos convidados deve estar bloqueado, pois o hotspot é IPv4. O backend não garante identidade do aparelho a partir de um MAC informado pelo cliente. O acesso temporário é vinculado ao MAC existente no roteador e tem limite/cooldown, mas prevenção completa contra spoofing exige autenticação adicional na rede. A separação entre clientes no mesmo switch exige isolamento de portas/VLAN no equipamento; firewall IP não isola tráfego de camada 2. IPv6 dos convidados deve estar bloqueado, pois o hotspot é IPv4.
+14
View File
@@ -838,6 +838,20 @@
return; return;
} }
if (d.authenticated) { if (d.authenticated) {
// Captive-portal assistants re-evaluate the network on top-level navigation.
// An API login plus a DOM update leaves some phones using the captive state.
// Navigate once per server window; reloading must never extend its deadline.
if (Number.isFinite(d.expiresAt) && d.expiresAt > Date.now() &&
sessionStorage.getItem('freeAccessConfirmedUntil') !== String(d.expiresAt)) {
sessionStorage.setItem('freeAccessConfirmedUntil', String(d.expiresAt));
const target = new URL(location.href);
target.searchParams.set('mac', mac);
target.searchParams.set('free', '1');
target.searchParams.set('access', String(d.expiresAt));
message.textContent = 'Acesso autorizado. Atualizando a conexão deste aparelho…';
window.location.replace(target.href);
return;
}
if (d.probeToken) verifyClientInternet(d.probeToken); if (d.probeToken) verifyClientInternet(d.probeToken);
sessionStorage.removeItem('freeLoginAttemptUntil'); sessionStorage.removeItem('freeLoginAttemptUntil');
clearInterval(window.freeAccessTimer); clearInterval(window.freeAccessTimer);
+39 -2
View File
@@ -8,8 +8,10 @@ const code=html.match(/<script>([\s\S]*?)<\/script>/)[1];
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true}) { async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true}) {
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]); const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',classList:{toggle(){},add(){},remove(){}},addEventListener(){},appendChild(){}}])); const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',classList:{toggle(){},add(){},remove(){}},addEventListener(){},appendChild(){}}]));
const requests=[],forms=[],intervals=[]; 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(){}}}; 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.fetch=async(path,options)=>{ sandbox.fetch=async(path,options)=>{
requests.push({path,options}); requests.push({path,options});
if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test'})}; if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test'})};
@@ -28,7 +30,7 @@ async function portal({search,storage={},access={ok:true,authenticated:true,seco
}; };
vm.runInNewContext(code,sandbox); vm.runInNewContext(code,sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r)); for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
return {requests,elements,forms,intervals,checkout:async()=>{ return {requests,elements,forms,intervals,navigations,checkout:async()=>{
elements.get('payerName').value='Teste Usuario';elements.get('payerEmail').value='[email protected]'; elements.get('payerName').value='Teste Usuario';elements.get('payerEmail').value='[email protected]';
await vm.runInNewContext('checkout("plano-1h")',sandbox); await vm.runInNewContext('checkout("plano-1h")',sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r)); for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
@@ -90,3 +92,38 @@ test('unsupported API login falls back to the hotspot form without claiming conf
assert.match(p.elements.get('freeAccessMessage').textContent,/ainda não confirmou/); assert.match(p.elements.get('freeAccessMessage').textContent,/ainda não confirmou/);
assert.equal(p.requests.filter(r=>r.path==='/api/access/report').length,0); 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,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('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);
});