From 0c01e5d88bcdd729bb4e6e8b32a03b7b2e7feed6 Mon Sep 17 00:00:00 2001 From: Jorge Fernando dos Santos Date: Thu, 22 Oct 2026 15:35:19 +0000 Subject: [PATCH] fix: confirm temporary hotspot login and show payment access countdown --- README.md | 2 +- backend/public/index.html | 50 ++++++++++++++++++++++++++++++++------ backend/src/index.js | 24 ++++++++++++------ backend/src/ros.js | 24 +++++++++++++++--- backend/test/admin.test.js | 28 +++++++++++++++++++-- 5 files changed, 105 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 9fe4608..e7a94f8 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hots ## Fluxo 1. O MikroTik redireciona o convidado para o portal, com `?mac=...`. -2. O backend pode criar uma conta temporária, vinculada ao MAC, para abrir o aplicativo do banco (120 segundos; intervalo mínimo de 300 segundos). +2. O backend cria uma conta temporária vinculada ao MAC e tenta autenticar o dispositivo pela API `/ip/hotspot/active/login`. Confirma a sessão no roteador antes de mostrar o contador para abrir o aplicativo do banco (120 segundos; intervalo mínimo de 300 segundos). Se a API de login não estiver disponível, tenta a tela de login do hotspot; falhas ficam visíveis no portal e nos logs `[ACESSO]`/`[ACESSO LOGIN]`. 3. O comprador escolhe o plano, informa nome/e-mail e gera o PIX. 4. O pagamento é confirmado consultando a API do Mercado Pago. O webhook assinado antecipa a consulta; há também polling a cada 15 segundos no backend e 6 segundos no portal. 5. O backend valida referência e valor pago e provisiona um voucher no MikroTik. Repetições reutilizam as credenciais persistidas. diff --git a/backend/public/index.html b/backend/public/index.html index 34075d5..5a90c9e 100644 --- a/backend/public/index.html +++ b/backend/public/index.html @@ -477,6 +477,10 @@ +
+

Verificando acesso temporário para pagamento…

+ +
@@ -804,9 +808,14 @@ // ===== Internet temporaria para pagar (login automatico no hotspot) ===== async function startFreeAccess() { - if (!mac) return; - if (sessionStorage.getItem('freeOk') || sessionStorage.getItem('freeTried')) return; - sessionStorage.setItem('freeTried', '1'); + const message = $('freeAccessMessage'); + const retry = $('retryFreeAccess'); + if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac)) { + message.textContent = 'Para liberar internet temporária, conecte ao Wi-Fi de convidados e abra o portal pela tela de entrada da rede.'; + return; + } + retry.hidden = true; + message.textContent = 'Preparando acesso temporário para abrir o aplicativo do banco…'; try { const res = await fetch('/api/access/start', { method: 'POST', @@ -814,14 +823,41 @@ body: JSON.stringify({ mac }), }); const d = await res.json(); - if (!res.ok) { sessionStorage.removeItem('freeTried'); return; } - if (d.loginUrl) { + if (!res.ok) { + message.textContent = res.status === 429 ? d.error + (d.retryAfterSeconds ? ' Tente em ' + d.retryAfterSeconds + ' segundos.' : '') : 'Não foi possível liberar a internet temporária. Tente novamente ou consulte o responsável pela rede.'; + retry.hidden = false; + return; + } + if (d.authenticated) { + sessionStorage.removeItem('freeLoginAttemptUntil'); + clearInterval(window.freeAccessTimer); + const deadline = Date.now() + d.seconds * 1000; + const update = () => { + const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000)); + message.textContent = seconds ? 'Sessão temporária confirmada: ' + seconds + ' segundos para efetuar o pagamento.' : 'O acesso temporário terminou. Se já pagou, toque em “Já paguei”.'; + if (!seconds) { clearInterval(window.freeAccessTimer); retry.hidden = false; } + }; + update(); window.freeAccessTimer = setInterval(update, 1000); + return; + } + message.textContent = 'O MikroTik ainda não confirmou o acesso. Tentando autenticar pela tela do hotspot…'; + retry.hidden = false; + if (d.loginUrl && Number(sessionStorage.getItem('freeLoginAttemptUntil') || 0) < Date.now()) { + sessionStorage.setItem('freeLoginAttemptUntil', String(Date.now() + d.seconds * 1000)); const target = new URL(d.loginUrl); hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst')); } - } catch { /* segue */ } + } catch { + message.textContent = 'Falha ao verificar o acesso temporário. Toque em tentar liberar acesso.'; + retry.hidden = false; + } } + $('retryFreeAccess').addEventListener('click', () => { + sessionStorage.removeItem('freeLoginAttemptUntil'); + startFreeAccess(); + }); + async function loadSiteConfig() { try { const res = await fetch('/api/config'); @@ -831,8 +867,6 @@ } catch { /* usa padrao */ } } - if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1'); - loadSiteConfig().then(startFreeAccess); loadPlans(); if (sessionStorage.getItem('paymentId')) { diff --git a/backend/src/index.js b/backend/src/index.js index 08913f2..7ba2a58 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -10,7 +10,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 { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js'; +import { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus, loginPaymentAccess } from './ros.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export const app = express(); @@ -54,12 +54,16 @@ app.post('/api/access/start', async (req, res) => { // reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas) if (prev && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) { - if (prev.expiresAt <= now) return res.status(429).json({ error: "Aguarde para um novo acesso temporário." }); - return res.json({ ok: true, seconds: Math.max(0, Math.ceil((prev.expiresAt - now) / 1000)), loginUrl: prev.loginUrl, reused: true }); + if (prev.expiresAt <= now || prev.revoked) return res.status(429).json({ error: 'O acesso temporário terminou. Aguarde para solicitar novamente.', retryAfterSeconds: Math.ceil((Date.parse(prev.createdAt) + config.freeAccessCooldownSeconds * 1000 - now) / 1000) }); + const previousUrl = new URL(prev.loginUrl); + let authenticated = false; + try { authenticated = await loginPaymentAccess({ mac, user: prev.user, pass: previousUrl.searchParams.get('password') }); } + catch (e) { console.error('[ACESSO LOGIN]', e.message); } + return res.json({ ok: true, seconds: Math.max(0, Math.ceil((prev.expiresAt - Date.now()) / 1000)), expiresAt: prev.expiresAt, authenticated, loginUrl: prev.loginUrl, reused: true }); } - const minutes = Math.max(1, Math.ceil(config.freeAccessSeconds / 60)); - const r = await allowPaymentAccess(mac, minutes); + const r = await allowPaymentAccess(mac, config.freeAccessSeconds); + const startedAt = Date.now(); const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1'); const loginUrl = @@ -73,12 +77,16 @@ app.post('/api/access/start', async (req, res) => { mac, user: r.user, loginUrl, - createdAt: new Date(now).toISOString(), - expiresAt: now + config.freeAccessSeconds * 1000, + createdAt: new Date(startedAt).toISOString(), + expiresAt: startedAt + config.freeAccessSeconds * 1000, }); saveDb(); - res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user }); + let authenticated = false; + try { authenticated = await loginPaymentAccess(r); } + catch (e) { console.error('[ACESSO LOGIN]', e.message); } + const expiresAt = startedAt + config.freeAccessSeconds * 1000; + res.json({ ok: true, seconds: Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000)), expiresAt, authenticated, loginUrl, user: r.user }); } catch (e) { console.error('[ACESSO]', e.message); res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' }); diff --git a/backend/src/ros.js b/backend/src/ros.js index f44cbf3..c19a443 100644 --- a/backend/src/ros.js +++ b/backend/src/ros.js @@ -175,14 +175,16 @@ async function ensureFreeProfile(rateLimit = '3M/3M') { 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}`]); + if (!id) throw new Error('Perfil pix-free sem identificador'); + await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`, `=session-timeout=${config.freeAccessSeconds}s`, '=add-mac-cookie=no']); 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}`]); + if (!id) throw new Error('Perfil pix-free não encontrado após criação'); + await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`, `=session-timeout=${config.freeAccessSeconds}s`, '=add-mac-cookie=no']); } catch (e) { throw new Error('Não foi possível preparar o perfil temporário', { cause: e }); } @@ -199,7 +201,7 @@ async function removeActiveByMac(mac) { } // Cria um usuario temporario do hotspot (o portal faz login automatico nele) -export async function allowPaymentAccess(mac, minutes = 10) { +export async function allowPaymentAccess(mac, seconds = config.freeAccessSeconds) { if (!mac) throw new Error('mac obrigatorio'); if (!await hostAddressByMac(mac)) throw new Error('Dispositivo não encontrado na rede do hotspot'); const sessions = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]); @@ -215,11 +217,25 @@ export async function allowPaymentAccess(mac, minutes = 10) { `=password=${pass}`, '=profile=pix-free', `=mac-address=${mac}`, - `=limit-uptime=${minutes}m`, + `=limit-uptime=${seconds}s`, ]); return { user: name, pass, mac }; } +export async function temporaryAccessActive(mac) { + const rows = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]); + return rows.some(row => pickField(row, '=user=') === freeUserName(mac) && pickField(row, '=server=') === config.mikrotik.server); +} + +export async function loginPaymentAccess({ mac, user, pass }) { + if (user !== freeUserName(mac)) throw new Error('Conta temporária inválida'); + if (await temporaryAccessActive(mac)) return true; + const ip = await hostAddressByMac(mac); + if (!ip) throw new Error('Dispositivo não encontrado no hotspot'); + await rosCommand(['/ip/hotspot/active/login', `=user=${user}`, `=password=${pass}`, `=ip=${ip}`, `=mac-address=${mac}`]); + return temporaryAccessActive(mac); +} + function pickField(row, key) { const v = (row || []).find((w) => w.startsWith(key)); return v ? v.slice(key.length) : null; diff --git a/backend/test/admin.test.js b/backend/test/admin.test.js index 6923875..7dba366 100644 --- a/backend/test/admin.test.js +++ b/backend/test/admin.test.js @@ -9,6 +9,9 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w const users=[{'.id':'*1',name:'existing',profile:'pix-1h',server:'guest-hotspot',disabled:'false',uptime:'1m','limit-uptime':'1h',comment:'=FORMULA()'}]; const active=[{'.id':'*A',user:'existing',server:'guest-hotspot',address:'10.10.10.10','mac-address':'AA:BB:CC:DD:EE:FF'}]; const cookies=[{'.id':'*B',user:'existing'}]; + const profiles=[{'.id':'*C',name:'pix-1h','rate-limit':'5M/1M'}]; + const commands=[]; + let denyLogin=false; let trap=false; function encode(words) { return Buffer.concat([...words.flatMap(w=>{const b=Buffer.from(w);return [b.length<128?Buffer.from([b.length]):Buffer.from([0x80 | b.length>>8,b.length&255]),b];}),Buffer.from([0])]); @@ -25,13 +28,20 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w const args=Object.fromEntries(cmd.slice(1).filter(w=>w[0]==='=').map(w=>{const i=w.indexOf('=',1);return[w.slice(1,i),w.slice(i+1)];})); if(cmd[0]==='/login'){socket.write(encode(['!done']));continue;} if(trap){socket.write(encode(['!trap','=message=simulated failure']));continue;} + commands.push(cmd); + if(cmd[0]==='/ip/hotspot/active/login' && denyLogin){socket.write(encode(['!trap','=message=no such command']));continue;} let rows=[]; if(cmd[0]==='/ip/hotspot/user/print') rows=users; if(cmd[0]==='/ip/hotspot/active/print') rows=active; if(cmd[0]==='/ip/hotspot/cookie/print') rows=cookies; - if(cmd[0]==='/ip/hotspot/user/profile/print') rows=[{name:'pix-1h','rate-limit':'5M/1M'}]; + if(cmd[0]==='/ip/hotspot/user/profile/print') rows=profiles; + if(cmd[0]==='/ip/hotspot/host/print') rows=[{address:'10.10.10.20','mac-address':'AA:BB:CC:DD:EE:11'},{address:'10.10.10.21','mac-address':'AA:BB:CC:DD:EE:22'}]; for(const query of cmd.filter(w=>w[0]==='?')){const i=query.indexOf('=');rows=rows.filter(r=>r[query.slice(1,i)]===query.slice(i+1));} - if(cmd[0]==='/ip/hotspot/user/add') users.push({'.id':'*2',...args,disabled:'false'}); + if(cmd[0]==='/ip/hotspot/user/add') users.push({'.id':'*'+(users.length+1).toString(16).toUpperCase(),...args,disabled:'false'}); + if(cmd[0]==='/ip/hotspot/user/remove') users.splice(users.findIndex(u=>u['.id']===args.numbers),1); + if(cmd[0]==='/ip/hotspot/user/profile/add') profiles.push({'.id':'*D',...args}); + if(cmd[0]==='/ip/hotspot/user/profile/set') Object.assign(profiles.find(p=>p['.id']===args.numbers),args); + if(cmd[0]==='/ip/hotspot/active/login') active.push({'.id':'*E',user:args.user,server:'guest-hotspot',address:args.ip,'mac-address':args['mac-address']}); if(cmd[0]==='/ip/hotspot/user/set') Object.assign(users.find(u=>u['.id']===args.numbers),{disabled:args.disabled==='yes'?'true':'false'}); if(cmd[0]==='/ip/hotspot/active/remove') active.splice(active.findIndex(a=>a['.id']===args.numbers),1); if(cmd[0]==='/ip/hotspot/cookie/remove') cookies.splice(cookies.findIndex(a=>a['.id']===args.numbers),1); @@ -65,6 +75,20 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w assert.equal((await request('/api/admin/plans','POST',{plans:[{price:-1}]})).status,400); assert.equal((await request('/api/mp/webhook','POST',{data:{id:'ORD1',status:'processed'}})).status,503); assert.equal((await fetch(base+'/api/admin/plans',{method:'POST',headers:{'Content-Type':'application/json'},body:'{'})).status,400); + // Temporary access is confirmed by RouterOS, bounded in seconds, and reused. + res=await request('/api/access/start','POST',{mac:'aa:bb:cc:dd:ee:11'});assert.equal(res.status,200); + const temporary=await res.json();assert.equal(temporary.authenticated,true);assert.ok(temporary.seconds>0 && temporary.seconds<=120); + const free=users.find(u=>u.name==='FREEAABBCCDDEE11');assert.equal(free['limit-uptime'],'120s');assert.equal(free['mac-address'],'AA:BB:CC:DD:EE:11'); + assert.equal(profiles.find(p=>p.name==='pix-free')['session-timeout'],'120s'); + const loginCount=commands.filter(c=>c[0]==='/ip/hotspot/active/login').length; + res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'});assert.equal((await res.json()).authenticated,true); + assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,loginCount); + const {getDb}=await import('../src/db.js');getDb().tempAccess.find(t=>t.mac==='AA:BB:CC:DD:EE:11').expiresAt=Date.now()-1; + assert.equal((await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'})).status,429); + denyLogin=true;res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:22'});const fallback=await res.json();assert.equal(fallback.authenticated,false);assert.ok(fallback.loginUrl); + denyLogin=false; + active.push({'.id':'*F',user:'paid-voucher',server:'guest-hotspot','mac-address':'AA:BB:CC:DD:EE:11'}); + const {revokePaymentAccess}=await import('../src/ros.js');await revokePaymentAccess('AA:BB:CC:DD:EE:11');assert.ok(active.some(a=>a.user==='paid-voucher'));assert.ok(!active.some(a=>a.user==='FREEAABBCCDDEE11')); trap=true;res=await request('/api/admin/users');assert.equal(res.status,500);assert.ok(!(await res.text()).includes('simulated failure')); const html=await fetch(base+'/admin');assert.equal(html.status,200);assert.ok((await html.text()).includes('Criar usuário')); });