fix: start payment internet window on demand and verify connectivity from guest browser
build-image / build-push (push) Successful in 2m41s

This commit is contained in:
jfeng committed 2026-10-22 16:11:45 +00:00
1 parent 0c01e5d88b
commit 783e241e42
7 files changed
+187 -8

No files matched your search

+5
View File
@@ -78,12 +78,17 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
// Temporary access is confirmed by RouterOS, bounded in seconds, and reused.
res=await request('/api/access/start','POST',{mac:'aa:bb:cc:dd:ee:11'});assert.equal(res.status,200);
const temporary=await res.json();assert.equal(temporary.authenticated,true);assert.ok(temporary.seconds>0 && temporary.seconds<=120);
assert.ok(temporary.probeToken);
const probeResults=[{provider:'google',ok:true},{provider:'apple',ok:false}];
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:'wrong',results:probeResults})).status,403);
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,200);
const free=users.find(u=>u.name==='FREEAABBCCDDEE11');assert.equal(free['limit-uptime'],'120s');assert.equal(free['mac-address'],'AA:BB:CC:DD:EE:11');
assert.equal(profiles.find(p=>p.name==='pix-free')['session-timeout'],'120s');
const loginCount=commands.filter(c=>c[0]==='/ip/hotspot/active/login').length;
res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'});assert.equal((await res.json()).authenticated,true);
assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,loginCount);
const {getDb}=await import('../src/db.js');getDb().tempAccess.find(t=>t.mac==='AA:BB:CC:DD:EE:11').expiresAt=Date.now()-1;
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,410);
assert.equal((await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'})).status,429);
denyLogin=true;res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:22'});const fallback=await res.json();assert.equal(fallback.authenticated,false);assert.ok(fallback.loginUrl);
denyLogin=false;
+86
View File
@@ -0,0 +1,86 @@
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}) {
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 requests=[],forms=[],intervals=[];
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.fetch=async(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/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()=>({status:'pending'})};
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/')) {
assert.equal(options.mode,'no-cors');assert.equal(options.redirect,'error');
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,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,/180 segundos/);
assert.equal(p.elements.get('retryFreeAccess').hidden,false);
});
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,/após gerar o PIX/);
});
test('temporary internet starts after PIX is generated and QR survives a reload',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.indexOf('/api/checkout')<paths.indexOf('/api/access/start'));
assert.match(p.elements.get('freeAccessMessage').textContent,/confirmada/);
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'));
});
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.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);
});