diff --git a/backend/public/index.html b/backend/public/index.html index 8147d0b..49269a2 100644 --- a/backend/public/index.html +++ b/backend/public/index.html @@ -783,7 +783,25 @@ window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent); }); + // ===== Internet temporaria para pagar (abre o app do banco) ===== + async function startFreeAccess() { + if (!mac) return; + try { + const res = await fetch('/api/access/start', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mac }), + }); + const d = await res.json(); + if (d.ok) { + const mins = Math.round((d.seconds / 60) * 10) / 10; + toast('Internet liberada por ' + mins + ' min para pagar'); + } + } catch { /* segue */ } + } + loadPlans(); + startFreeAccess(); diff --git a/backend/src/config.js b/backend/src/config.js index adea511..0976443 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -15,6 +15,7 @@ const config = { server: process.env.MIKROTIK_SERVER || 'guest-hotspot', }, port: parseInt(process.env.PORT || '3000', 10), + freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 90), baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000', adminToken: process.env.ADMIN_TOKEN || 'dev-token', dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'), diff --git a/backend/src/db.js b/backend/src/db.js index 0be5f69..4a26a0d 100644 --- a/backend/src/db.js +++ b/backend/src/db.js @@ -11,7 +11,7 @@ const DEFAULT_PLANS = [ { id: 'plano-7d', name: '7 Dias', price: 15.00, profile: 'pix-7d', uptime: '1w', speed: '10M/3M', active: true }, ]; -let db = { plans: [], payments: [] }; +let db = { plans: [], payments: [], tempAccess: [] }; export function initDb() { fs.mkdirSync(config.dataDir, { recursive: true }); @@ -19,8 +19,9 @@ export function initDb() { db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8')); if (!db.plans?.length) db.plans = structuredClone(DEFAULT_PLANS); if (!db.payments) db.payments = []; + if (!db.tempAccess) db.tempAccess = []; } else { - db = { plans: structuredClone(DEFAULT_PLANS), payments: [] }; + db = { plans: structuredClone(DEFAULT_PLANS), payments: [], tempAccess: [] }; saveDb(); } } diff --git a/backend/src/index.js b/backend/src/index.js index 1386391..5bae1d2 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'; import config from './config.js'; import { initDb, getDb, saveDb, genCode } from './db.js'; import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js'; -import { createHotspotUser } from './ros.js'; +import { createHotspotUser, allowPaymentAccess, revokePaymentAccess } from './ros.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const app = express(); @@ -23,6 +23,9 @@ async function fulfill(payment) { payment.voucher = { user, pass }; payment.status = 'paid'; payment.paidAt = new Date().toISOString(); + const db = getDb(); + db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== payment.mac); + if (payment.mac) revokePaymentAccess(payment.mac).catch(() => {}); saveDb(); console.log(`[PAGA] ${payment.planId} -> voucher ${user}`); return payment; @@ -45,6 +48,39 @@ async function checkPayment(payment) { // ===== Rotas ===== +// ===== Internet temporaria para pagar (bypass do hotspot) ===== +app.post('/api/access/start', async (req, res) => { + const { mac } = req.body || {}; + if (!mac) return res.status(400).json({ error: 'mac obrigatorio' }); + try { + const r = await allowPaymentAccess(mac); + const now = Date.now(); + const db = getDb(); + db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== mac); + db.tempAccess.push({ + mac, + ip: r.ip, + createdAt: new Date(now).toISOString(), + expiresAt: now + config.freeAccessSeconds * 1000, + }); + saveDb(); + res.json({ ok: true, seconds: config.freeAccessSeconds, ip: r.ip }); + } catch (e) { + console.error('[ACESSO]', e.message); + res.status(500).json({ error: e.message }); + } +}); + +// ===== Reconciliacao manual (caso o webhook falhe) ===== +app.post('/api/reconcile', async (req, res) => { + const { orderId } = req.body || {}; + if (!orderId) return res.status(400).json({ error: 'orderId obrigatorio' }); + const payment = getDb().payments.find((p) => String(p.mpId) === String(orderId)); + if (!payment) return res.status(404).json({ error: 'pedido nao encontrado' }); + await checkPayment(payment); + res.json({ status: payment.status, voucher: payment.voucher, orderId: payment.mpId }); +}); + app.get('/api/plans', (req, res) => { res.json(getDb().plans.filter((p) => p.active)); }); @@ -115,7 +151,7 @@ app.post('/api/checkout', async (req, res) => { app.post('/api/mp/webhook', async (req, res) => { res.sendStatus(200); // responde rápido para o MP não reenviar try { - const mpId = req.body?.data?.id || req.query?.['data.id']; + const mpId = req.body?.data?.id || req.body?.id || req.query?.['data.id'] || req.query?.id; if (!mpId) return; const payment = getDb().payments.find((p) => String(p.mpId) === String(mpId)); if (!payment) { @@ -190,6 +226,18 @@ setInterval(async () => { for (const p of pendings) await checkPayment(p); }, 15000); +// ===== Expira acessos temporarios de pagamento ===== +setInterval(async () => { + const db = getDb(); + const now = Date.now(); + const expired = (db.tempAccess || []).filter((t) => t.expiresAt <= now); + if (!expired.length) return; + for (const t of expired) await revokePaymentAccess(t.mac).catch(() => {}); + db.tempAccess = (db.tempAccess || []).filter((t) => t.expiresAt > now); + saveDb(); + console.log(`[ACESSO] ${expired.length} liberacao(oes) temporaria(s) expirada(s)`); +}, 15000); + app.listen(config.port, '0.0.0.0', () => { console.log(`pix-hotspot rodando em ${config.baseUrl} (porta ${config.port})`); console.log(`MikroTik: ${config.mikrotik.host}:${config.mikrotik.port}`); diff --git a/backend/src/mp.js b/backend/src/mp.js index 6c29220..f5f826d 100644 --- a/backend/src/mp.js +++ b/backend/src/mp.js @@ -159,9 +159,11 @@ export async function getPaymentStatus(mpId) { try { if (isOrder) { const data = await new Order(getClient()).get({ id: mpId }); + const pay = data.transactions?.payments?.[0] || {}; // order: action_required (waiting_transfer) = pendente | processed = pago - if (data.status === 'processed') return 'approved'; - if (data.status === 'cancelled' || data.status === 'rejected') return data.status; + if (data.status === 'processed' || pay.status === 'approved') return 'approved'; + if (['cancelled', 'rejected', 'expired', 'refunded'].includes(data.status)) return data.status; + if (['cancelled', 'rejected', 'refunded'].includes(pay.status)) return pay.status; return 'pending'; } const data = await new Payment(getClient()).get({ id: mpId }); diff --git a/backend/src/ros.js b/backend/src/ros.js index 502aa41..1074dba 100644 --- a/backend/src/ros.js +++ b/backend/src/ros.js @@ -133,6 +133,61 @@ export async function createHotspotUser(name, password, profile, uptime) { await rosCommand(words); } +// ===== Acesso temporario para pagamento ===== +// Libera internet (bypass do hotspot) por alguns minutos, com limite de banda, +// para o convidado abrir o app do banco e pagar o PIX. + +async function hostAddressByMac(mac) { + try { + const replies = await rosCommand(['/ip/hotspot/host/print', `?mac-address=${mac}`]); + const row = (replies || [])[0] || []; + const addr = row.find((w) => w.startsWith('=address=')); + return addr ? addr.slice(9) : null; + } catch { + return null; + } +} + +export async function allowPaymentAccess(mac, speed = '3M/3M') { + if (!mac) throw new Error('mac obrigatorio'); + const ip = await hostAddressByMac(mac); + + // bypass do hotspot por MAC (funciona mesmo antes do login) + try { + await rosCommand(['/ip/hotspot/ip-binding/add', `=mac-address=${mac}`, '=type=bypassed', '=comment=pix-pagando']); + } catch (e) { + if (!/already|duplicate/i.test(e.message)) throw e; + } + + // limite de banda para essa liberacao temporaria + if (ip) { + try { + await rosCommand(['/queue/simple/add', `=name=pixpagando-${mac}`, `=target=${ip}/32`, `=max-limit=${speed}`]); + } catch (e) { + if (!/already|duplicate/i.test(e.message)) throw e; + } + } + return { ip, mac }; +} + +export async function revokePaymentAccess(mac) { + if (!mac) return; + try { + const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]); + for (const row of bindings || []) { + const id = row.find((w) => w.startsWith('=.id=')); + if (id) await rosCommand(['/ip/hotspot/ip-binding/remove', `=numbers=${id.slice(5)}`]); + } + } catch { /* ignora */ } + try { + const queues = await rosCommand(['/queue/simple/print', `?name=pixpagando-${mac}`]); + for (const row of queues || []) { + const id = row.find((w) => w.startsWith('=.id=')); + if (id) await rosCommand(['/queue/simple/remove', `=numbers=${id.slice(5)}`]); + } + } catch { /* ignora */ } +} + export async function mikrotikPing() { const replies = await rosCommand(['/system/identity/print']); return replies?.[0]?.find((w) => w.startsWith('=name='))?.slice(6) || 'ok';