Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f377455009 | ||
|
|
a4e3d1ff56 | ||
|
|
9165731fec | ||
|
|
f97ff6066e | ||
|
|
b3a3e26562 | ||
|
|
67bbafdc41 | ||
|
|
64add2bc68 | ||
|
|
f8235b55b0 | ||
|
|
228afc59ce | ||
|
|
d12005d588 | ||
|
|
384c443b88 | ||
|
|
b854c40232 | ||
|
|
be92d48ca0 | ||
|
|
8962de008e |
No files matched your search
@@ -1,50 +1,21 @@
|
||||
name: build-download
|
||||
|
||||
name: diagnose-hotspot-access
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-download:
|
||||
diagnose:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build image
|
||||
run: |
|
||||
docker build -t git.jf.eng.br/jfeng/hotspot:latest -t git.jf.eng.br/jfeng/hotspot:${{ github.sha }} ./backend
|
||||
|
||||
- name: Smoke test image
|
||||
- uses: actions/checkout@v4
|
||||
- name: Production diagnosis and database write check
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
container=$(docker run -d git.jf.eng.br/jfeng/hotspot:${{ github.sha }})
|
||||
trap 'docker rm -f "$container" >/dev/null' EXIT
|
||||
for attempt in {1..15}; do
|
||||
if docker exec "$container" node -e "fetch('http://127.0.0.1:3000/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"; then
|
||||
docker exec "$container" node -e "Promise.all(['/api/plans','/admin'].map(p=>fetch('http://127.0.0.1:3000'+p).then(r=>{if(!r.ok)throw Error(p)}))).catch(()=>process.exit(1))"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
docker logs "$container"
|
||||
exit 1
|
||||
|
||||
- name: Export Docker archive
|
||||
docker inspect pix-hotspot --format 'IMAGE={{.Config.Image}} PORTS={{json .NetworkSettings.Ports}}'
|
||||
docker exec -i pix-hotspot node --input-type=module < backend/diagnose-hotspot.mjs
|
||||
- name: Recent sanitized errors
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker save git.jf.eng.br/jfeng/hotspot:latest git.jf.eng.br/jfeng/hotspot:${{ github.sha }} | gzip > pix-hotspot-image.tar.gz
|
||||
sha256sum pix-hotspot-image.tar.gz > pix-hotspot-image.tar.gz.sha256
|
||||
|
||||
- name: Upload image for ZimaOS
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: pix-hotspot-zimaos
|
||||
path: |
|
||||
pix-hotspot-image.tar.gz
|
||||
pix-hotspot-image.tar.gz.sha256
|
||||
retention-days: 7
|
||||
docker logs --since 2h --tail 3000 pix-hotspot 2>&1 | node -e 'let s="";process.stdin.on("data",x=>s+=x);process.stdin.on("end",()=>console.log(s.split("\n").filter(l=>/\[(ACESSO|CHECKOUT|LIMPEZA|HTTP)/.test(l)).slice(-60).map(l=>l.replace(/(?:[0-9a-f]{2}:){5}[0-9a-f]{2}/gi,"[MAC]").replace(/(?:\d{1,3}\.){3}\d{1,3}/g,"[IP]").replace(/(?:APP_USR|TEST)-[\w-]+/g,"[TOKEN]").replace(/[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}/g,"[EMAIL]").slice(0,700)).join("\n")));'
|
||||
@@ -0,0 +1,36 @@
|
||||
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
Line truncated
|
||||
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');
|
||||
Reference in new issue
Block a user