fix: repair hotspot redirect and mapped portal port with timed live verification
This commit is contained in:
1 parent
b854c40232
commit
384c443b88
1 file changed
+58
-17
@@ -25,23 +25,64 @@ try {
|
||||
console.log('TEMP-RECORDS',JSON.stringify((db.tempAccess||[]).map(t=>({device:hash(t.mac),createdAt:t.createdAt,expiresAt:t.expiresAt,revoked:t.revoked}))));
|
||||
} catch(e){console.log('DB-ERROR',redact(e.message));}
|
||||
|
||||
{
|
||||
for(const [label,words] of [
|
||||
['DNS',['/ip/dns/print','=.proplist=servers,dynamic-servers,allow-remote-requests']],
|
||||
['DHCP-NETWORK',['/ip/dhcp-server/network/print','=.proplist=address,gateway,dns-server']],
|
||||
['NAT',['/ip/firewall/nat/print','=.proplist=chain,action,disabled,comment,src-address,dst-address,out-interface,dst-port,to-addresses,to-ports,protocol']],
|
||||
['DEFAULT-ROUTE',['/ip/route/print','?dst-address=0.0.0.0/0','=.proplist=gateway,active,distance']],
|
||||
['INTERNET-PING',['/ping','=address=1.1.1.1','=count=3']],
|
||||
['TRAFFIC',['/ip/hotspot/active/print','=.proplist=mac-address,user,uptime,session-time-left,bytes-in,bytes-out,packets-in,packets-out']],
|
||||
]){
|
||||
try{console.log(label,redact(JSON.stringify((await rosCommand(words)).map(object))));}
|
||||
catch(e){console.log(label+'-ERROR',redact(e.message));}
|
||||
const source=fs.readFileSync('/app/src/ros.js','utf8').replace("from './config.js'","from 'file:///app/src/config.js'").replace("else if (attr === '!done') this.done = true;","else if (attr === '!done') { this.done = true; if (words.length > 1) this.replies.push(words.slice(1)); }");
|
||||
const {rosCommand:rawRos}=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
|
||||
const readContent=async id=>(await rawRos(['/file/get','=number='+id,'=value-name=contents'])).flat().find(v=>v.startsWith('=ret='))?.slice(5)||'';
|
||||
const fixedAlogin="<!DOCTYPE html>\n<html lang=\"pt-BR\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta http-equiv=\"refresh\" content=\"0;url=$(link-redirect)\">\n <title>INCTG — Acesso autorizado</title>\n</head>\n<body>\n <p>Acesso autorizado. <a href=\"$(link-redirect)\">Continuar para o portal</a>.</p>\n</body>\n</html>";
|
||||
const fileRows=(await rawRos(['/file/print','=.proplist=.id,name'])).map(object);
|
||||
const alogin=fileRows.find(f=>f.name==='hotspot/alogin.html'||f.name==='flash/hotspot/alogin.html');
|
||||
if(!alogin)throw new Error('alogin.html not found; refusing automatic changes');
|
||||
const oldAlogin=await readContent(alogin['.id']);
|
||||
if(!oldAlogin.includes('$(link-redirect)')&&!(oldAlogin.includes('https://hotspot.jf.eng.br/?mac=$(mac)')&&oldAlogin.length<3000))throw new Error('Unexpected alogin contents; manual review required');
|
||||
const updates=[];
|
||||
for(const commandPath of ['/ip/firewall/filter','/ip/hotspot/walled-garden/ip']){
|
||||
const rows=(await rawRos([commandPath+'/print','=.proplist=.id,chain,comment,dst-address,dst-port,protocol'])).map(object);
|
||||
for(const row of rows){
|
||||
if(row.comment==='pix: portal pagamento' && (row['dst-address']||'').replace('/32','')==='192.168.3.100' && row['dst-port']==='3000' && row.protocol==='tcp' && (commandPath!=='/ip/firewall/filter'||row.chain==='forward')){
|
||||
updates.push({path:commandPath,id:row['.id'],previousPort:'3000',port:'8905'});
|
||||
}
|
||||
const hosts=(await rosCommand(['/ip/hotspot/host/print','=.proplist=address,mac-address,server,authorized,bypassed'])).map(object).filter(h=>h.server===config.mikrotik.server);
|
||||
const connections=(await rosCommand(['/ip/firewall/connection/print','=.proplist=src-address,dst-address,seen-reply,protocol,tcp-state'])).map(object);
|
||||
for(const h of hosts){
|
||||
const c=connections.filter(c=>(c['src-address']||'').split(':')[0]===h.address);
|
||||
const internet=c.filter(c=>!/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(c['dst-address']||''));
|
||||
console.log('DEVICE-TRAFFIC-SUMMARY',JSON.stringify({device:hash(h['mac-address']),authorized:h.authorized,connections:c.length,internetConnections:internet.length,internetWithReplies:internet.filter(c=>c['seen-reply']==='true').length,dnsWithReplies:internet.filter(c=>(c['dst-address']||'').endsWith(':53')&&c['seen-reply']==='true').length}));
|
||||
}
|
||||
}
|
||||
const backupName=config.dataDir+'/hotspot-access-before-fix-'+new Date().toISOString().replace(/[:.]/g,'-')+'.json';
|
||||
fs.writeFileSync(backupName,JSON.stringify({at:new Date().toISOString(),alogin:{id:alogin['.id'],name:alogin.name,contents:oldAlogin},updates},null,2),{mode:0o600});
|
||||
if(process.getuid?.()===0)fs.chownSync(backupName,1000,1000);
|
||||
const applied=[];
|
||||
let changedAlogin=false;
|
||||
try{
|
||||
if(!oldAlogin.includes('$(link-redirect)')){
|
||||
await rawRos(['/file/set','=numbers='+alogin['.id'],'=contents='+fixedAlogin]);changedAlogin=true;
|
||||
if((await readContent(alogin['.id'])).trim()!==fixedAlogin.trim())throw new Error('alogin verification failed');
|
||||
}
|
||||
for(const update of updates){
|
||||
await rawRos([update.path+'/set','=numbers='+update.id,'=dst-port='+update.port]);applied.push(update);
|
||||
}
|
||||
}catch(e){
|
||||
for(const update of applied.reverse())await rawRos([update.path+'/set','=numbers='+update.id,'=dst-port='+update.previousPort]).catch(()=>{});
|
||||
if(changedAlogin)await rawRos(['/file/set','=numbers='+alogin['.id'],'=contents='+oldAlogin]).catch(()=>{});
|
||||
throw e;
|
||||
}
|
||||
console.log('TARGETED-REPAIR',JSON.stringify({backup:backupName,aloginChanged:changedAlogin,portRulesChanged:updates.length,portalPort:8905}));
|
||||
const portalResponse=await fetch(config.baseUrl,{signal:AbortSignal.timeout(20000)});
|
||||
const portalHtml=await portalResponse.text();
|
||||
console.log('PUBLIC-PORTAL',JSON.stringify({status:portalResponse.status,hasAccessUi:portalHtml.includes('freeAccessMessage'),hasAutomaticCall:portalHtml.includes('loadSiteConfig().then(startFreeAccess)'),macRequired:portalHtml.includes("get('mac')")}));
|
||||
const hosts=(await rosCommand(['/ip/hotspot/host/print','=.proplist=address,mac-address,server,authorized,bypassed'])).map(object).filter(h=>h.server===config.mikrotik.server&&h.authorized!=='true'&&h.bypassed!=='true');
|
||||
if(hosts.length!==1)throw new Error('Need exactly one unauthenticated guest for live validation; found '+hosts.length);
|
||||
const mac=hosts[0]['mac-address'];
|
||||
const request=()=>fetch(config.baseUrl+'/api/access/start',{method:'POST',headers:{'Content-Type':'application/json',Origin:config.baseUrl},body:JSON.stringify({mac}),signal:AbortSignal.timeout(25000)});
|
||||
const response=await request();const d=await response.json();
|
||||
console.log('PUBLIC-ACCESS-START',JSON.stringify({status:response.status,device:hash(mac),authenticated:d.authenticated,seconds:d.seconds,retryAfterSeconds:d.retryAfterSeconds,error:d.error}));
|
||||
if(!response.ok||!d.authenticated)throw new Error('Public access request did not produce an authenticated session');
|
||||
const rows=async()=>(await rosCommand(['/ip/hotspot/active/print','?mac-address='+mac,'=.proplist=user,server,uptime,session-time-left,bytes-in,bytes-out'])).map(object);
|
||||
console.log('SESSION-T0',JSON.stringify((await rows()).map(r=>({...r,user:'account-'+hash(r.user)}))));
|
||||
const reused=await request();const again=await reused.json();
|
||||
if(!again.reused||!again.authenticated||again.expiresAt!==d.expiresAt)throw new Error('Reuse extended or lost the original session');
|
||||
console.log('REUSE-VERIFIED',JSON.stringify({status:reused.status,seconds:again.seconds,unchangedExpiry:again.expiresAt===d.expiresAt}));
|
||||
await new Promise(resolve=>setTimeout(resolve,Math.max(0,d.expiresAt-Date.now()+7000)));
|
||||
const remaining=await rows();
|
||||
console.log('SESSION-AFTER-EXPIRY',JSON.stringify(remaining.map(r=>({...r,user:'account-'+hash(r.user)}))));
|
||||
const temporaryStillActive=remaining.some(r=>(r.user||'').startsWith('FREE'));
|
||||
if(temporaryStillActive)throw new Error('Temporary session remained active past deadline');
|
||||
const cooldown=await request();const c=await cooldown.json();
|
||||
console.log('COOLDOWN-VERIFIED',JSON.stringify({status:cooldown.status,retryAfterSeconds:c.retryAfterSeconds,error:c.error}));
|
||||
if(cooldown.status!==429)throw new Error('Cooldown did not reject a new temporary grant');
|
||||
console.log('LIVE-VALIDATION-PASS',JSON.stringify({publicRequest:true,routerSession:true,expiry:true,cooldown:true,physicalDeviceInternetStillRequiresClientConfirmation:true}));
|
||||
Reference in new issue
Block a user