37 lines
16 KiB
JavaScript
37 lines
16 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));}
|
|
|
|
const source="import net from 'node:net';\nimport config from 'file:///app/src/config.js';\nimport crypto from 'node:crypto';\n\nfunction packLen(n) {\n if (n < 0x80) return Buffer.from([n]);\n if (n < 0x4000) return Buffer.from([0x80 | (n >> 8), n & 0xff]);\n if (n < 0x200000) return Buffer.from([0xc0 | (n >> 16), (n >> 8) & 0xff, n & 0xff]);\n if (n < 0x10000000) return Buffer.from([0xe0 | (n >> 24), (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);\n return Buffer.from([0xf0, (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);\n}\n\nfunction encodeSentence(words) {\n const parts = [];\n for (const w of words) {\n const buf = Buffer.from(String(w), 'utf8');\n parts.push(packLen(buf.length), buf);\n }\n parts.push(Buffer.from([0]));\n return Buffer.concat(parts);\n}\n\nclass Parser {\n constructor() {\n this.buf = Buffer.alloc(0);\n this.words = [];\n this.sentence = [];\n this.done = false;\n this.error = null;\n this.replies = [];\n }\n push(chunk) {\n this.buf = Buffer.concat([this.buf, chunk]);\n if (this.buf.length > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS excede o limite'; return; }\n while (true) {\n if (this.buf.length === 0) return;\n const first = this.buf[0];\n let len, offset;\n if ((first & 0x80) === 0) { len = first; offset = 1; }\n else if ((first & 0xc0) === 0x80) {\n if (this.buf.length < 2) return;\n len = ((first & 0x3f) << 8) | this.buf[1]; offset = 2;\n } else if ((first & 0xe0) === 0xc0) {\n if (this.buf.length < 3) return;\n len = ((first & 0x1f) << 16) | (this.buf[1] << 8) | this.buf[2]; offset = 3;\n } else if ((first & 0xf0) === 0xe0) {\n if (this.buf.length < 4) return;\n len = ((first & 0x0f) << 24) | (this.buf[1] << 16) | (this.buf[2] << 8) | this.buf[3]; offset = 4;\n } else if (first === 0xf0) {\n if (this.buf.length < 5) return;\n len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;\n } else { this.error = 'Comprimento RouterOS inválido'; return; }\n if (len < 0 || len > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS inválida'; return; }\n if (this.buf.length < offset + len) return;\n const data = this.buf.subarray(offset, offset + len);\n this.buf = this.buf.subarray(offset + len);\n if (len === 0) {\n if (this.sentence.length > 0) {\n this.handleSentence(this.sentence);\n this.sentence = [];\n } else if (this.words.length > 0) {\n this.handleSentence(this.words);\n this.words = [];\n }\n if (this.done || this.error) return;\n } else {\n this.words.push(data.toString('utf8'));\n }\n }\n }\n handleSentence(words) {\n const attr = words[0];\n if (attr === '!re') this.replies.push(words.slice(1));\n else if (attr === '!done') this.done = true;\n else if (attr === '!trap') this.error = words.slice(1).join(' ') || 'trap';\n else if (attr === '!fatal') this.error = 'RouterOS encerrou a conexão';\n else this.replies.push(words);\n }\n}\n\nexport async function rosCommand(words, timeoutMs = 8000) {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n const parser = new Parser();\n let settled = false;\n const finish = (err, val) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n socket.destroy();\n err ? reject(err) : resolve(val);\n };\n const timer = setTimeout(() => finish(new Error('timeout MikroTik API')), timeoutMs);\n socket.on('error', (e) => finish(e));\n socket.on('close', () => {\n if (!settled) finish(new Error('conexao MikroTik fechada'));\n });\n socket.connect(config.mikrotik.port, config.mikrotik.host, () => {\n socket.write(encodeSentence(['/login', `=name=${config.mikrotik.user}`, `=password=${config.mikrotik.password}`]));\n const onLogin = (chunk) => {\n parser.push(chunk);\n if (parser.error) { socket.off('data', onLogin); return finish(new Error(parser.error)); }\n if (parser.done) {\n socket.off('data', onLogin);\n // login ok - recria parser e envia comando\n const p2 = new Parser();\n const onData2 = (c2) => {\n p2.push(c2);\n if (p2.error) finish(new Error(p2.error));\n else if (p2.done) finish(null, p2.replies);\n };\n socket.on('data', onData2);\n socket.write(encodeSentence(words));\n } else if (parser.replies.length && parser.replies.some(r => r.some(w => w.startsWith('=ret=')))) {\n finish(new Error('RouterOS antigo (<6.43): use login simples - atualize o RouterOS'));\n }\n };\n socket.on('data', onLogin);\n });\n });\n}\n\nexport async function createHotspotUser(name, password, profile, uptime, comment = 'pix:manual') {\n const words = [\n '/ip/hotspot/user/add',\n `=server=${config.mikrotik.server}`,\n `=name=${name}`,\n `=password=${password}`,\n `=profile=${profile}`,\n `=comment=${comment}`,\n ];\n if (uptime) words.push(`=limit-uptime=${uptime}`);\n await rosCommand(words);\n}\n\n// ===== Acesso temporario para pagamento =====\n// Libera internet (bypass do hotspot) por alguns minutos, com limite de banda,\n// para o convidado abrir o app do banco e pagar o PIX.\n\nasync function hostAddressByMac(mac) {\n const pick = (replies, key) => {\n for (const row of replies || []) {\n const v = row.find((w) => w.startsWith(key));\n if (v) return v.slice(key.length);\n }\n return null;\n };\n try {\n const replies = await rosCommand(['/ip/hotspot/host/print', `?mac-address=${mac}`]);\n const addr = pick(replies, '=address=');\n if (addr) return addr;\n } catch { /* segue */ }\n try {\n const leases = await rosCommand(['/ip/dhcp-server/lease/print', `?mac-address=${mac}`]);\n return pick(leases, '=address=');\n } catch {\n return null;\n }\n}\n\nfunction freeUserName(mac) {\n return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').toUpperCase();\n}\n\nasync function removeUserByName(name) {\n const rows = await rosCommand(['/ip/hotspot/user/print', `?name=${name}`]);\n for (const row of rows || []) {\n const id = pickField(row, '=.id=');\n if (id) await rosCommand(['/ip/hotspot/user/remove', `=numbers=${id}`]);\n }\n}\n\nasync function ensureFreeProfile(rateLimit = '3M/3M') {\n try {\n const rows = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']);\n if (rows && rows.length) {\n const id = pickField(rows[0], '=.id=');\n if (!id) throw new Error('Perfil pix-free sem identificador');\n await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`, `=session-timeout=${config.freeAccessSeconds}s`, '=add-mac-cookie=no']);\n return;\n }\n // neste RouterOS o rate-limit nao e aceito no add: cria e depois define\n await rosCommand(['/ip/hotspot/user/profile/add', '=name=pix-free', '=shared-users=1']);\n const again = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']);\n const id = pickField((again || [])[0], '=.id=');\n if (!id) throw new Error('Perfil pix-free não encontrado após criação');\n await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`, `=session-timeout=${config.freeAccessSeconds}s`, '=add-mac-cookie=no']);\n } catch (e) {\n throw new Error('Não foi possível preparar o perfil temporário', { cause: e });\n }\n}\n\nasync function removeActiveByMac(mac) {\n try {\n const rows = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n for (const row of rows || []) {\n const id = pickField(row, '=.id=');\n if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);\n }\n } catch { /* ignora */ }\n}\n\n// Cria um usuario temporario do hotspot (o portal faz login automatico nele)\nexport async function allowPaymentAccess(mac, seconds = config.freeAccessSeconds) {\n if (!mac) throw new Error('mac obrigatorio');\n if (!await hostAddressByMac(mac)) throw new Error('Dispositivo não encontrado na rede do hotspot');\n const sessions = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n if (sessions.some(row => pickField(row, '=user=') !== freeUserName(mac))) throw new Error('Dispositivo já possui uma sessão autenticada');\n await ensureFreeProfile();\n const name = freeUserName(mac);\n const pass = crypto.randomBytes(16).toString('hex');\n await removeUserByName(name);\n await rosCommand([\n '/ip/hotspot/user/add',\n `=server=${config.mikrotik.server}`,\n `=name=${name}`,\n `=password=${pass}`,\n '=profile=pix-free',\n `=mac-address=${mac}`,\n `=limit-uptime=${seconds}s`,\n ]);\n return { user: name, pass, mac };\n}\n\nexport async function temporaryAccessActive(mac) {\n const rows = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n return rows.some(row => pickField(row, '=user=') === freeUserName(mac) && pickField(row, '=server=') === config.mikrotik.server);\n}\n\nexport async function loginPaymentAccess({ mac, user, pass }) {\n if (user !== freeUserName(mac)) throw new Error('Conta temporária inválida');\n if (await temporaryAccessActive(mac)) return true;\n const ip = await hostAddressByMac(mac);\n if (!ip) throw new Error('Dispositivo não encontrado no hotspot');\n await rosCommand(['/ip/hotspot/active/login', `=user=${user}`, `=password=${pass}`, `=ip=${ip}`, `=mac-address=${mac}`]);\n return temporaryAccessActive(mac);\n}\n\n// Promote the same connected device to its paid voucher without a browser login.\nexport async function activatePaidAccess(payment) {\n const { mac, voucher } = payment;\n if (!mac || !voucher) return false;\n const sessions = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n const own = sessions.filter(row => pickField(row, '=server=') === config.mikrotik.server);\n if (own.some(row => pickField(row, '=user=') === voucher.user)) return true;\n // Never disconnect a different paid account or another hotspot server.\n if (sessions.some(row => pickField(row, '=user=') !== freeUserName(mac) || pickField(row, '=server=') !== config.mikrotik.server)) return false;\n const ip = own.map(row => pickField(row, '=address=')).find(Boolean) || await hostAddressByMac(mac);\n if (!ip) return false;\n for (const row of own) {\n const id = pickField(row, '=.id=');\n if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);\n }\n await rosCommand(['/ip/hotspot/active/login', `=user=${voucher.user}`, `=password=${voucher.pass}`, `=ip=${ip}`, `=mac-address=${mac}`]);\n const active = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n return active.some(row => pickField(row, '=user=') === voucher.user && pickField(row, '=server=') === config.mikrotik.server);\n}\n\nfunction pickField(row, key) {\n const v = (row || []).find((w) => w.startsWith(key));\n return v ? v.slice(key.length) : null;\n}\n\nexport async function paymentAccessStatus(mac) {\n const out = { mac, binding: null, ip: null, active: null };\n try {\n const b = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);\n if (b && b.length) out.binding = { type: pickField(b[0], '=type='), comment: pickField(b[0], '=comment=') };\n } catch { /* ignora */ }\n out.ip = await hostAddressByMac(mac);\n try {\n const a = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);\n if (a && a.length) out.active = { address: pickField(a[0], '=address='), uptime: pickField(a[0], '=uptime=') };\n } catch { /* ignora */ }\n return out;\n}\n\nexport async function revokePaymentAccess(mac) {\n if (!mac) return;\n // Disconnect only the temporary account, never the paid voucher for this MAC.\n const active = await rosCommand(['/ip/hotspot/active/print', `?user=${freeUserName(mac)}`]);\n for (const row of active) {\n const id = pickField(row, '=.id=');\n if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);\n }\n await removeUserByName(freeUserName(mac));\n}\n\nexport async function mikrotikPing() {\n const replies = await rosCommand(['/system/identity/print']);\n return replies?.[0]?.find((w) => w.startsWith('=name='))?.slice(6) || 'ok';\n}\n";
|
|
const {activatePaidAccess}=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
|
|
const db=JSON.parse(fs.readFileSync(config.dataDir+'/db.json','utf8'));
|
|
const payment=db.payments.filter(p=>p.status==='paid'&&p.voucher&&p.mac&&Date.parse(p.paidAt)>Date.now()-24*3600000).at(-1);
|
|
if(payment){
|
|
console.log('PAID-HANDOFF-RESULT',JSON.stringify({device:hash(payment.mac),active:await activatePaidAccess(payment)}));
|
|
const active=(await rosCommand(['/ip/hotspot/active/print','?mac-address='+payment.mac])).map(object);
|
|
console.log('PAID-HANDOFF-SESSION',JSON.stringify(active.map(a=>({device:hash(a['mac-address']),paidUser:a.user===payment.voucher.user,server:a.server,uptime:a.uptime,remaining:a['session-time-left']}))));
|
|
}else console.log('NO-RECENT-PAID-PAYMENT');
|