Validate automatic activation using the existing approved voucher

This commit is contained in:
jfeng committed 2026-10-22 17:52:43 +00:00
1 parent a4e3d1ff56
commit f377455009
1 file changed
+8 -2
+8 -2
View File
@@ -25,6 +25,12 @@ 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));}
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'));
console.log('PAYMENT-HANDOFF',JSON.stringify(db.payments.slice(-8).map(p=>({id:hash(p.id),status:p.status,device:p.mac?hash(p.mac):null,hasVoucher:!!p.voucher,paidAt:p.paidAt,connection:p.connection||null}))));
console.log('ACCESS-CONFIG',JSON.stringify({seconds:config.freeAccessSeconds,cooldown:config.freeAccessCooldownSeconds}));
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');