diff --git a/backend/public/index.html b/backend/public/index.html index a8e0b46..c1c5878 100644 --- a/backend/public/index.html +++ b/backend/public/index.html @@ -602,8 +602,6 @@ let toastTimer = null; let selectedPlanId = null; let mpDevice = null; - let freeTimer = null; - let freeGrants = 0; const $ = (id) => document.getElementById(id); @@ -655,8 +653,7 @@ $('view-pay').classList.toggle('hidden', view !== 'pay'); $('view-voucher').classList.toggle('hidden', view !== 'voucher'); if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; } - if (view !== 'pay' && freeTimer) { clearInterval(freeTimer); freeTimer = null; } - if (view === 'pay' && !freeTimer) { freeTimer = setInterval(startFreeAccess, 120000); } + window.scrollTo({ top: 0, behavior: 'instant' in window ? 'auto' : 'auto' }); } @@ -787,11 +784,11 @@ window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent); }); - // ===== Internet temporaria para pagar (abre o app do banco) ===== + // ===== Internet temporaria para pagar (login automatico no hotspot) ===== async function startFreeAccess() { if (!mac) return; - if (freeGrants >= 12) return; - freeGrants++; + if (sessionStorage.getItem('freeOk') || sessionStorage.getItem('freeTried')) return; + sessionStorage.setItem('freeTried', '1'); try { const res = await fetch('/api/access/start', { method: 'POST', @@ -799,10 +796,7 @@ 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'); - } + if (d.loginUrl) window.location.href = d.loginUrl; } catch { /* segue */ } } @@ -814,6 +808,8 @@ } catch { /* usa padrao */ } } + if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1'); + loadSiteConfig(); loadPlans(); startFreeAccess(); diff --git a/backend/src/config.js b/backend/src/config.js index 79bc9f0..76267f4 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -15,8 +15,10 @@ const config = { server: process.env.MIKROTIK_SERVER || 'guest-hotspot', }, port: parseInt(process.env.PORT || '3000', 10), - freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 600), + freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 120), + freeAccessCooldownSeconds: Number(process.env.FREE_ACCESS_COOLDOWN_SECONDS || 300), ssidName: process.env.SSID_NAME || 'Internet Gratis', + hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1', 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/index.js b/backend/src/index.js index 4f620d0..131fed2 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -53,18 +53,36 @@ 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(); + const prev = (db.tempAccess || []).find((t) => t.mac === mac); + + // reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas) + if (prev && prev.loginUrl && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) { + return res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl: prev.loginUrl, reused: true }); + } + + const minutes = Math.max(1, Math.round(config.freeAccessSeconds / 60)); + const r = await allowPaymentAccess(mac, minutes); + + const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1'); + const loginUrl = + `http://${config.hotspotIp}/login` + + `?username=${encodeURIComponent(r.user)}` + + `&password=${encodeURIComponent(r.pass)}` + + `&dst=${back}`; + db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== mac); db.tempAccess.push({ mac, - ip: r.ip, + user: r.user, + loginUrl, createdAt: new Date(now).toISOString(), expiresAt: now + config.freeAccessSeconds * 1000, }); saveDb(); - res.json({ ok: true, seconds: config.freeAccessSeconds, ip: r.ip }); + + res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user }); } catch (e) { console.error('[ACESSO]', e.message); res.status(500).json({ error: e.message }); diff --git a/backend/src/ros.js b/backend/src/ros.js index 25858e1..e6511e4 100644 --- a/backend/src/ros.js +++ b/backend/src/ros.js @@ -87,11 +87,6 @@ async function rosCommand(words, timeoutMs = 8000) { err ? reject(err) : resolve(val); }; const timer = setTimeout(() => finish(new Error('timeout MikroTik API')), timeoutMs); - socket.on('data', (chunk) => { - parser.push(chunk); - if (parser.error) finish(new Error(parser.error)); - else if (parser.done) finish(null, parser.replies); - }); socket.on('error', (e) => finish(e)); socket.on('close', () => { if (!settled) finish(new Error('conexao MikroTik fechada')); @@ -158,26 +153,64 @@ async function hostAddressByMac(mac) { } } -export async function allowPaymentAccess(mac, speed = '3M/3M') { - if (!mac) throw new Error('mac obrigatorio'); - const ip = await hostAddressByMac(mac); +function freeUserName(mac) { + return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').slice(-10).toUpperCase(); +} - // bypass do hotspot por MAC (funciona mesmo antes do login) +async function removeUserByName(name) { 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; + const rows = await rosCommand(['/ip/hotspot/user/print', `?name=${name}`]); + for (const row of rows || []) { + const id = pickField(row, '=.id='); + if (id) await rosCommand(['/ip/hotspot/user/remove', `=numbers=${id}`]); } + } catch { /* ignora */ } +} + +async function ensureFreeProfile(rateLimit = '3M/3M') { + try { + const rows = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']); + if (rows && rows.length) { + const id = pickField(rows[0], '=.id='); + if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]); + return; + } + // neste RouterOS o rate-limit nao e aceito no add: cria e depois define + await rosCommand(['/ip/hotspot/user/profile/add', '=name=pix-free', '=shared-users=1']); + const again = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']); + const id = pickField((again || [])[0], '=.id='); + if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]); + } catch (e) { + console.error('[PERFIL pix-free]', e.message); } - return { ip, mac }; +} + +async function removeActiveByMac(mac) { + try { + const rows = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]); + for (const row of rows || []) { + const id = pickField(row, '=.id='); + if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]); + } + } catch { /* ignora */ } +} + +// Cria um usuario temporario do hotspot (o portal faz login automatico nele) +export async function allowPaymentAccess(mac, minutes = 10) { + if (!mac) throw new Error('mac obrigatorio'); + await ensureFreeProfile(); + const name = freeUserName(mac); + const pass = 'F' + Math.random().toString(36).slice(2, 9).toUpperCase(); + await removeUserByName(name); + await rosCommand([ + '/ip/hotspot/user/add', + `=server=${config.mikrotik.server}`, + `=name=${name}`, + `=password=${pass}`, + '=profile=pix-free', + `=limit-uptime=${minutes}m`, + ]); + return { user: name, pass, mac }; } function pickField(row, key) { @@ -201,6 +234,8 @@ export async function paymentAccessStatus(mac) { export async function revokePaymentAccess(mac) { if (!mac) return; + await removeActiveByMac(mac); + await removeUserByName(freeUserName(mac)); try { const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]); for (const row of bindings || []) {