Files
HotSpot/backend/diagnose-hotspot.mjs
T

55 lines
5.1 KiB
JavaScript

import fs from 'node:fs';
import crypto from 'node:crypto';
import config from '/app/src/config.js';
import { rosCommand } from '/app/src/ros.js';
const hash=v=>crypto.createHash('sha256').update(String(v)).digest('hex').slice(0,10);
const redact=s=>String(s).replace(/(?:[0-9a-f]{2}:){5}[0-9a-f]{2}/gi,m=>'device-'+hash(m)).replace(/(?:\d{1,3}\.){3}\d{1,3}/g,m=>m.split('.').slice(0,3).join('.')+'.x');
const object=row=>Object.fromEntries(row.filter(v=>v[0]==='=').map(v=>{const i=v.indexOf('=',1);return [v.slice(1,i),v.slice(i+1)];}));
console.log('CONFIG',JSON.stringify({routerHost:config.mikrotik.host,routerPort:config.mikrotik.port,routerUser:config.mikrotik.user,server:config.mikrotik.server,hotspotIp:config.hotspotIp,baseUrl:config.baseUrl,port:config.port,freeSeconds:config.freeAccessSeconds,cooldown:config.freeAccessCooldownSeconds,processUid:fs.readFileSync('/proc/1/status','utf8').match(/^Uid:.*$/m)?.[0]}));
for(const [label,words] of [
['RESOURCE',['/system/resource/print','=.proplist=version,architecture-name,board-name']],
['HOTSPOTS',['/ip/hotspot/print','=.proplist=name,interface,profile,disabled']],
['HOTSPOT-PROFILES',['/ip/hotspot/profile/print','=.proplist=name,login-by,hotspot-address,dns-name,html-directory']],
['FREE-PROFILE',['/ip/hotspot/user/profile/print','?name=pix-free','=.proplist=.id,name,rate-limit,session-timeout,shared-users,add-mac-cookie']],
['API-USER',['/user/print','?name='+config.mikrotik.user,'=.proplist=name,group,disabled']],
['HOSTS',['/ip/hotspot/host/print','=.proplist=address,to-address,mac-address,server,authorized,bypassed']],
['ACTIVE',['/ip/hotspot/active/print','=.proplist=user,address,mac-address,server,uptime,session-time-left']],
['FREE-USERS',['/ip/hotspot/user/print','?profile=pix-free','=.proplist=name,server,profile,disabled,limit-uptime,uptime,mac-address']],
['FILTER',['/ip/firewall/filter/print','=.proplist=chain,action,disabled,comment,in-interface,out-interface,src-address,dst-address,protocol,dst-port,connection-state,jump-target']],
]) {
try {const rows=(await rosCommand(words)).map(object);console.log(label,redact(JSON.stringify(rows.map(r=>label==='ACTIVE'||label==='FREE-USERS'?{...r,user:r.user?'account-'+hash(r.user):undefined,name:r.name?'account-'+hash(r.name):undefined}:r))));}
catch(e){console.log(label+'-ERROR',redact(e.message));}
}
try {
const db=JSON.parse(fs.readFileSync(config.dataDir+'/db.json','utf8'));
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));}
console.log('DEPLOYED',JSON.stringify({directLogin:fs.readFileSync('/app/src/index.js','utf8').includes('loginPaymentAccess'),countdown:fs.readFileSync('/app/public/index.html','utf8').includes('freeAccessMessage')}));
{
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 files=(await rawRos(['/file/print','=.proplist=.id,name,type,size'])).map(object);
for(const suffix of ['login.html','alogin.html']){
const f=files.find(f=>f.name==='hotspot/'+suffix||f.name==='flash/hotspot/'+suffix);
if(!f){console.log('HOTSPOT-FILE',suffix,'missing');continue;}
try {
const rows=await rawRos(['/file/get','=number='+f['.id'],'=value-name=contents']);
const content=rows.flat().find(v=>v.startsWith('=ret='))?.slice(5)||'';
console.log('HOTSPOT-FILE',JSON.stringify({file:f.name,length:content.length,hasMacVariable:content.includes('$(mac)'),hasDstVariable:/link-redirect|link-orig|dst=/.test(content),redirectionUrls:[...new Set(content.match(/https?:[^"'<>\s]+/g)||[])]}));
}catch(e){console.log('HOTSPOT-FILE-ERROR',suffix,redact(e.message));}
}
}
{
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){console.log('LIVE-TEST-SKIPPED','Expected exactly one unauthenticated device, found '+hosts.length);}
else {
const h=hosts[0];const mac=h['mac-address'];
const response=await fetch('http://127.0.0.1:'+config.port+'/api/access/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({mac})});
const d=await response.json();
console.log('LIVE-ACCESS-RESPONSE',redact(JSON.stringify({device:hash(mac),status:response.status,ok:d.ok,authenticated:d.authenticated,seconds:d.seconds,expiresAt:d.expiresAt,fallbackAvailable:!!d.loginUrl,error:d.error,retryAfterSeconds:d.retryAfterSeconds})));
const active=(await rosCommand(['/ip/hotspot/active/print','?mac-address='+mac,'=.proplist=user,server,uptime,session-time-left'])).map(object);
console.log('LIVE-DEVICE-ACTIVE',JSON.stringify(active.map(a=>({...a,user:a.user?'account-'+hash(a.user):undefined}))));
}
}