Activate paid Wi-Fi automatically and redesign portal with payment deadline and 45-minute wait
build-image / build-push (push) Successful in 2m59s
build-image / build-push (push) Successful in 2m59s
This commit is contained in:
1 parent
b69b3afa5d
commit
ce6e5980ec
10 files changed
+189
-37
No files matched your search
@@ -52,6 +52,7 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
|
||||
});
|
||||
await new Promise(r=>ros.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>ros.close(r)));
|
||||
process.env.NODE_ENV='test';process.env.MIKROTIK_HOST='127.0.0.1';process.env.MIKROTIK_PORT=String(ros.address().port);process.env.ADMIN_TOKEN='a'.repeat(48);
|
||||
process.env.FREE_ACCESS_COOLDOWN_SECONDS='300'; // Existing ZimaOS installations must also enforce 45 minutes.
|
||||
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'hotspot-test-'));process.env.DATA_DIR=dataDir;
|
||||
t.after(()=>fs.rmSync(dataDir,{recursive:true,force:true}));
|
||||
const { app }=await import('../src/index.js');
|
||||
@@ -60,6 +61,7 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
|
||||
const request=(url,method='GET',body)=>fetch(base+url,{method,headers:{'x-admin-token':process.env.ADMIN_TOKEN,'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
assert.equal((await fetch(base+'/api/admin/users')).status,401);
|
||||
const { default: config } = await import('../src/config.js');
|
||||
assert.equal(config.freeAccessCooldownSeconds,2700);
|
||||
const originalToken = config.adminToken;
|
||||
config.adminToken = 'replace-with-at-least-32-random-characters';
|
||||
assert.equal((await request('/api/admin/users')).status,503);
|
||||
@@ -89,9 +91,21 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
|
||||
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);
|
||||
const cooldownResponse=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'});
|
||||
assert.equal(cooldownResponse.status,429);
|
||||
assert.ok((await cooldownResponse.json()).retryAfterSeconds>=2700);
|
||||
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;
|
||||
const {activatePaidAccess}=await import('../src/ros.js');
|
||||
const paid={mac:'AA:BB:CC:DD:EE:11',voucher:{user:'purchased-voucher',pass:'paid-password'}};
|
||||
assert.equal(await activatePaidAccess(paid),true);
|
||||
assert.ok(active.some(a=>a.user==='purchased-voucher'));
|
||||
assert.ok(!active.some(a=>a.user==='FREEAABBCCDDEE11'));
|
||||
const paidLoginCount=commands.filter(c=>c[0]==='/ip/hotspot/active/login').length;
|
||||
assert.equal(await activatePaidAccess(paid),true);
|
||||
assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,paidLoginCount);
|
||||
assert.equal(await activatePaidAccess({...paid,voucher:{user:'different-paid-account',pass:'other'}}),false);
|
||||
assert.ok(active.some(a=>a.user==='purchased-voucher'));
|
||||
active.push({'.id':'*F',user:'paid-voucher',server:'guest-hotspot','mac-address':'AA:BB:CC:DD:EE:11'});
|
||||
const {revokePaymentAccess}=await import('../src/ros.js');await revokePaymentAccess('AA:BB:CC:DD:EE:11');assert.ok(active.some(a=>a.user==='paid-voucher'));assert.ok(!active.some(a=>a.user==='FREEAABBCCDDEE11'));
|
||||
trap=true;res=await request('/api/admin/users');assert.equal(res.status,500);assert.ok(!(await res.text()).includes('simulated failure'));
|
||||
|
||||
@@ -5,13 +5,14 @@ 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}) {
|
||||
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true,clipboardAvailable=true,legacyCopy=false,consent=true,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:'',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 || '');
|
||||
elements.get('accessConsent').checked=consent;
|
||||
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=()=>{};
|
||||
@@ -19,11 +20,11 @@ async function portal({search,storage={},access={ok:true,authenticated:true,seco
|
||||
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'})};
|
||||
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()=>({status:'pending'})};
|
||||
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.
|
||||
@@ -58,7 +59,7 @@ test('direct portal URL without MAC cannot silently claim temporary access',asyn
|
||||
});
|
||||
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.match(p.elements.get('freeAccessMessage').textContent,/3 minutos/);
|
||||
assert.equal(p.elements.get('retryFreeAccess').hidden,false);
|
||||
});
|
||||
test('browsing plans does not consume the payment internet window',async()=>{
|
||||
@@ -164,3 +165,25 @@ test('an expired or denied window cannot navigate, and a new window can revalida
|
||||
const next=await portal({search,storage,access:{ok:true,authenticated:true,seconds:120,expiresAt:Date.now()+120000}});
|
||||
assert.equal(next.navigations.length,1);
|
||||
});
|
||||
|
||||
test('rules use the configured payment duration and require acknowledgement before access',async()=>{
|
||||
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',consent:false,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/);
|
||||
await p.checkout();await p.click('copyBtn');
|
||||
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
|
||||
assert.match(p.elements.get('freeAccessMessage').textContent,/confirme acima/);
|
||||
p.elements.get('accessConsent').checked=true;
|
||||
await p.click('retryFreeAccess');
|
||||
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -54,3 +54,24 @@ test('unconfirmed payments never provision users', async () => {
|
||||
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{throw new Error('MP unavailable');},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
|
||||
const p={id:'P3',mpId:'ORD3',status:'pending'};await svc.checkPayment(p);assert.equal(creates,0);assert.equal(p.status,'pending');
|
||||
});
|
||||
|
||||
test('paid handoff retries without another charge or voucher and preserves temporary access until connected',async()=>{
|
||||
const temp={mac:'AA:BB:CC:DD:EE:11',expiresAt:Date.now()+120000};
|
||||
const originalExpiry=temp.expiresAt;
|
||||
const p={id:'P4',mpId:'ORD4',status:'pending',profile:'pix-1h',uptime:'1h',mac:temp.mac};
|
||||
let queries=0,creates=0,attempts=0;
|
||||
const svc=paymentService({getDb:()=>({tempAccess:[temp]}),saveDb:()=>{},getPaymentStatus:async()=>{queries++;return 'approved';},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;},activatePaidAccess:async payment=>{
|
||||
assert.equal(payment.status,'paid');assert.ok(payment.voucher);
|
||||
if(++attempts===1)throw new Error('Router temporarily unavailable');
|
||||
return true;
|
||||
}});
|
||||
await svc.checkPayment(p);
|
||||
assert.equal(p.status,'paid');assert.equal(p.connection.state,'pending');
|
||||
assert.equal(temp.expiresAt,originalExpiry);
|
||||
const voucher=p.voucher;
|
||||
await Promise.all([svc.checkPayment(p),svc.checkPayment(p)]);
|
||||
assert.equal(p.connection.state,'active');assert.equal(p.voucher,voucher);
|
||||
assert.ok(temp.expiresAt<=Date.now());assert.equal(queries,1);assert.equal(creates,1);
|
||||
const completedAttempts=attempts;
|
||||
await svc.checkPayment(p);assert.equal(attempts,completedAttempts);
|
||||
});
|
||||
Reference in new issue
Block a user