feat: add hotspot admin panel and harden payment provisioning
build-image / build-push (push) Failing after 1m36s

This commit is contained in:
jfeng committed 2026-10-22 14:01:08 +00:00
1 parent fb3135d18f
commit ebb2d1d792
25 files changed
+832 -686

No files matched your search

+4 -2
View File
@@ -1,9 +1,11 @@
FROM node:20-alpine
FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install --omit=dev
RUN npm ci --omit=dev
COPY src ./src
COPY public ./public
ENV NODE_ENV=production
RUN mkdir -p /app/data && chown -R node:node /app
USER node
EXPOSE 3000
CMD ["node", "src/index.js"]
+7 -64
View File
@@ -8,8 +8,8 @@
"name": "pix-hotspot-backend",
"version": "1.0.0",
"dependencies": {
"express": "^4.19.2",
"mercadopago": "^2.13.0"
"express": "4.22.3",
"mercadopago": "3.6.1"
}
},
"node_modules/accepts": {
@@ -461,12 +461,11 @@
}
},
"node_modules/mercadopago": {
"version": "2.13.0",
"resolved": "https://registry.npmjs.org/mercadopago/-/mercadopago-2.13.0.tgz",
"integrity": "sha512-dm096v3Mu2VcW6j3/YJIiIAuGzzUwtGGnNga+SmfK55lpY28r1m7Zi3JyRVxSWtrwYWHT0rKs6ni05gc2kUmDw==",
"dependencies": {
"node-fetch": "^2.7.0",
"uuid": "^9.0.0"
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/mercadopago/-/mercadopago-3.6.1.tgz",
"integrity": "sha512-JFgKCSRHMxkS1p12VMIcpI/Zki739J+5lbpl7PB0O8WHaFl4SFKQnm9paX/gqBQeh211Ozc498D49Fbe3U1jEw==",
"engines": {
"node": ">=18"
}
},
"node_modules/merge-descriptors": {
@@ -535,26 +534,6 @@
"node": ">= 0.6"
}
},
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -818,12 +797,6 @@
"node": ">=0.6"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
@@ -855,20 +828,6 @@
"node": ">= 0.4.0"
}
},
"node_modules/uuid": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
"deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@@ -877,22 +836,6 @@
"engines": {
"node": ">= 0.8"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
}
}
}
+4 -3
View File
@@ -5,10 +5,11 @@
"type": "module",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js"
"start": "node src/index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.19.2",
"mercadopago": "^2.13.0"
"express": "4.22.3",
"mercadopago": "3.6.1"
}
}
+1
View File
@@ -0,0 +1 @@
:root{color-scheme:dark;--bg:#101820;--card:#17232e;--line:#2b3c4c;--text:#f4f6f8;--muted:#a4b2c0;--blue:#246bfd}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,sans-serif}header,main,footer{max-width:1280px;margin:auto;padding:24px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}header strong{font-size:25px;letter-spacing:.06em}header span{color:#82aaff}header p{margin:0;color:var(--muted)}a{color:#9bbbff}h1{font-size:32px;line-height:1.2;margin:8px 0 12px}h2{font-size:20px;margin:0 0 8px}p{color:var(--muted);margin:6px 0 18px}.eyebrow{font-size:12px;font-weight:700;letter-spacing:.15em;color:#82aaff}.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:24px;margin-bottom:20px}.login{max-width:520px;margin:8vh auto}.login label{margin:24px 0 16px}.login button{width:100%;margin-bottom:18px}small{color:var(--muted)}label{display:flex;flex-direction:column;gap:8px;font-size:13px;font-weight:600}input,select,button{font:inherit;border-radius:8px;min-height:44px;padding:10px 14px}input,select{background:#101820;color:var(--text);border:1px solid #486078;width:100%}button{background:var(--blue);color:white;font-weight:650;border:1px solid transparent;cursor:pointer}button:hover{filter:brightness(1.14)}button:disabled{opacity:.5;cursor:wait}.secondary{background:transparent;border-color:#486078}.danger{background:#652e3a;border-color:#c76a7c}.toolbar,.section-title{display:flex;justify-content:space-between;align-items:center;gap:18px}.actions{display:flex;gap:10px}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.metrics span{display:block;color:var(--muted);font-size:13px}.metrics strong{display:block;font-size:30px;margin-top:8px}.filters{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin:18px 0}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:14px}th{text-align:left;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}td,th{padding:14px 12px;border-bottom:1px solid var(--line);vertical-align:top}td small{display:block}.badge{display:inline-block;padding:3px 9px;border-radius:20px;background:#2a3a4b;font-size:12px;white-space:nowrap}.badge.online{background:#174b3f;color:#9fecd3}.badge.blocked{background:#5b2934;color:#ffc2cc}.create-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;align-items:end}.notice{padding:18px;margin-top:20px;border:1px solid #4488ff;border-radius:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}#message{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);max-width:90vw;width:600px;background:#243b53;border:1px solid #82aaff;padding:16px 22px;border-radius:12px;color:white;box-shadow:0 8px 30px #0008;z-index:10}#message.error{background:#542634;border-color:#e992a5}footer{color:var(--muted);text-align:center;font-size:12px}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #a0bcff;outline-offset:3px}[hidden]{display:none!important}@media(max-width:750px){header,main,footer{padding:16px}.card{padding:18px}.metrics{grid-template-columns:repeat(2,1fr);gap:10px}.toolbar,.section-title{align-items:flex-start;flex-direction:column}.filters,.create-grid{grid-template-columns:1fr}.login{margin:30px auto}h1{font-size:27px}td,th{padding:12px 8px}}
+28
View File
@@ -0,0 +1,28 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Administração • INCTG Wi-Fi</title>
<link rel="stylesheet" href="/admin.css">
<script src="/admin.js" defer></script>
</head>
<body>
<header><div><strong>INCTG <span>Wi-Fi</span></strong><p>Administração do hotspot</p></div><a href="/">Abrir portal ↗</a></header>
<main>
<section id="login" class="card login"><p class="eyebrow">ACESSO RESTRITO</p><h1>Seu hotspot, sob controle.</h1><p>Entre com o ADMIN_TOKEN configurado no servidor.</p>
<form id="loginForm"><label>Token administrativo<input id="token" type="password" autocomplete="off" required minlength="32"></label><button>Entrar no painel</button></form><small>O token permanece apenas na memória desta aba. Ao sair ou recarregar, entre novamente.</small></section>
<div id="dashboard" hidden>
<div class="toolbar"><div><p class="eyebrow">VISÃO GERAL</p><h1>Usuários e pagamentos</h1><p id="updated">Carregando…</p></div><div class="actions"><button id="refresh" class="secondary">Atualizar</button><button id="logout" class="secondary">Sair</button></div></div>
<div class="metrics"><article class="card"><span>Usuários</span><strong id="total">—</strong></article><article class="card"><span>Online</span><strong id="online">—</strong></article><article class="card"><span>Bloqueados</span><strong id="blocked">—</strong></article><article class="card"><span>Pagamentos aprovados*</span><strong id="revenue">—</strong></article></div>
<section class="card"><div class="section-title"><div><h2>Usuários do hotspot</h2><p>Bloquear também encerra sessões e remove cookies de acesso.</p></div><button id="export" class="secondary">Exportar CSV</button></div>
<div class="filters"><label>Buscar<input id="search" type="search" placeholder="Usuário, perfil, IP ou MAC"></label><label>Situação<select id="filter"><option value="all">Todos</option><option value="online">Online</option><option value="blocked">Bloqueados</option><option value="offline">Offline</option></select></label></div>
<div class="table-wrap"><table><thead><tr><th>Usuário / perfil</th><th>Situação</th><th>Dispositivo</th><th>Tempo usado / limite</th><th>Tráfego</th><th>Ação</th></tr></thead><tbody id="users"></tbody></table></div><p id="empty" hidden>Nenhum usuário encontrado.</p></section>
<section class="card"><h2>Criar usuário</h2><p>O limite corresponde ao tempo acumulado de conexão. Deixe a senha vazia para gerar uma automaticamente.</p>
<form id="createForm" class="create-grid"><label>Usuário<input name="name" required pattern="[A-Za-z0-9_.@-]{1,64}" maxlength="64" placeholder="visitante-01"></label><label>Perfil<select id="profile" name="profile" required></select></label><label>Limite de uso<input name="uptime" required value="1h" placeholder="1h, 1d ou 1w"></label><label>Senha<input name="password" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="Gerar automaticamente"></label><label>Observação<input name="comment" maxlength="200"></label><button>Criar usuário</button></form>
<div id="credentials" class="notice" hidden><strong>Usuário criado. Guarde as credenciais:</strong><pre id="newCredentials"></pre><button id="hideCredentials" class="secondary">Ocultar</button></div></section>
<section class="card"><h2>Pagamentos recentes</h2><p>*Total referente aos últimos 100 registros, sem representar um fechamento contábil.</p><div class="table-wrap"><table><thead><tr><th>Data</th><th>Plano</th><th>Valor</th><th>Status</th><th>Voucher</th></tr></thead><tbody id="payments"></tbody></table></div></section>
<section class="card"><h2>Atividade administrativa</h2><div class="table-wrap"><table><thead><tr><th>Data</th><th>Ação</th><th>Usuário / quantidade</th></tr></thead><tbody id="audit"></tbody></table></div></section>
</div>
<p id="message" role="status" aria-live="polite" hidden></p>
</main><footer>INCTG · Tecnologia que resolve.</footer>
</body></html>
+95
View File
@@ -0,0 +1,95 @@
'use strict';
let token = '';
let users = [];
let noticeTimer;
const $ = id => document.getElementById(id);
function message(text, error = false) {
$('message').textContent = text; $('message').className = error ? 'error' : ''; $('message').hidden = false;
clearTimeout(noticeTimer); noticeTimer = setTimeout(() => $('message').hidden = true, 8000);
}
function logout() {
token = ''; users = []; $('token').value = ''; $('login').hidden = false; $('dashboard').hidden = true;
for (const id of ['users', 'payments', 'audit', 'newCredentials']) $(id).replaceChildren();
$('credentials').hidden = true;
}
async function api(path, options = {}) {
const res = await fetch('/api/admin' + path, { ...options, headers: { 'x-admin-token': token, ...(options.body ? { 'Content-Type': 'application/json' } : {}) }, cache: 'no-store' });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
if (res.status === 401) logout();
throw new Error(data.error || 'Não foi possível concluir a operação.');
}
return res;
}
function cell(row, text) { const td = document.createElement('td'); td.textContent = text ?? '—'; row.append(td); return td; }
function date(value) { return value ? new Date(value).toLocaleString('pt-BR') : '—'; }
function renderUsers() {
const q = $('search').value.trim().toLowerCase(), filter = $('filter').value;
const visible = users.filter(u => JSON.stringify(u).toLowerCase().includes(q) && (filter === 'all' || filter === 'blocked' && u.disabled || filter === 'online' && u.sessions.length || filter === 'offline' && !u.sessions.length));
$('users').replaceChildren(); $('empty').hidden = visible.length > 0;
for (const u of visible) {
const row = document.createElement('tr');
const name = cell(row, u.name); const profile = document.createElement('small'); profile.textContent = u.profile; name.append(profile);
const state = cell(row, ''); const badge = document.createElement('span'); badge.className = 'badge ' + (u.disabled ? 'blocked' : u.sessions.length ? 'online' : ''); badge.textContent = u.disabled ? 'Bloqueado' : u.sessions.length ? 'Online' : 'Offline'; state.append(badge);
cell(row, u.sessions.map(s => [s.ip, s.mac].filter(Boolean).join(' · ')).join('\n') || '—');
cell(row, u.uptime + ' / ' + (u.limitUptime === '0s' ? 'Sem limite' : u.limitUptime));
cell(row, ((u.bytesIn + u.bytesOut) / 1048576).toFixed(1) + ' MB');
const action = cell(row, ''); const button = document.createElement('button'); button.className = u.disabled ? 'secondary' : 'danger'; button.textContent = u.disabled ? 'Desbloquear' : 'Bloquear';
button.onclick = async () => {
if (!u.disabled && !confirm('Bloquear ' + u.name + ' e encerrar suas sessões?')) return;
button.disabled = true;
try { await api('/users/' + encodeURIComponent(u.id), { method: 'PATCH', body: JSON.stringify({ disabled: !u.disabled }) }); await refresh(); message('Usuário atualizado.'); }
catch (e) { message(e.message + ' Atualize a lista para conferir o estado atual.', true); }
finally { button.disabled = false; }
};
action.append(button); $('users').append(row);
}
}
async function refresh() {
$('refresh').disabled = true;
try {
const results = await Promise.allSettled(['/users', '/payments', '/profiles', '/audit'].map(async path => (await api(path)).json()));
if (!token) return;
const errors = results.map((r, i) => r.status === 'rejected' ? ['Usuários', 'Pagamentos', 'Perfis', 'Atividade'][i] + ': ' + r.reason.message : null).filter(Boolean);
if (results[0].status === 'fulfilled') {
users = results[0].value; renderUsers(); $('total').textContent = users.length; $('online').textContent = users.filter(u => u.sessions.length).length; $('blocked').textContent = users.filter(u => u.disabled).length;
} else { users = []; renderUsers(); for (const id of ['total','online','blocked']) $(id).textContent = '—'; }
$('payments').replaceChildren(); $('revenue').textContent = '—';
if (results[1].status === 'fulfilled') {
const payments = results[1].value;
$('revenue').textContent = payments.filter(p => p.status === 'paid').reduce((n,p) => n + p.price,0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
for (const p of payments) { const row = document.createElement('tr'); [date(p.createdAt), p.planId, Number(p.price).toLocaleString('pt-BR',{style:'currency',currency:'BRL'}), p.status, p.voucher?.user || '—'].forEach(v => cell(row,v)); $('payments').append(row); }
}
if (results[2].status === 'fulfilled') {
const selected = $('profile').value; $('profile').replaceChildren();
for (const p of results[2].value) { const o = document.createElement('option'); o.value = p.name; o.textContent = p.name + (p.rateLimit ? ' · ' + p.rateLimit : ''); $('profile').append(o); }
if ([...$('profile').options].some(o => o.value === selected)) $('profile').value = selected;
}
$('audit').replaceChildren();
if (results[3].status === 'fulfilled') for (const a of results[3].value) { const row = document.createElement('tr'); [date(a.at),a.action,a.target].forEach(v => cell(row,v)); $('audit').append(row); }
$('updated').textContent = 'Última consulta: ' + new Date().toLocaleTimeString('pt-BR') + (errors.length ? ' · Há dados indisponíveis' : '');
if (errors.length) message(errors.join(' | '), true);
} finally { $('refresh').disabled = false; }
}
$('loginForm').onsubmit = async event => {
event.preventDefault(); token = $('token').value.trim(); const button = event.submitter; button.disabled = true;
try { await api('/audit'); $('token').value = ''; $('login').hidden = true; $('dashboard').hidden = false; await refresh(); }
catch (e) { message(e.message, true); } finally { button.disabled = false; }
};
$('logout').onclick = logout;
$('refresh').onclick = () => refresh().catch(e => message(e.message,true));
$('search').oninput = renderUsers; $('filter').onchange = renderUsers;
$('createForm').onsubmit = async event => {
event.preventDefault(); const button = event.submitter; button.disabled = true;
try {
const data = Object.fromEntries(new FormData(event.target));
const created = await (await api('/users',{method:'POST',body:JSON.stringify(data)})).json();
$('newCredentials').textContent = 'Usuário: ' + created.name + '\nSenha: ' + created.password; $('credentials').hidden = false; event.target.reset(); await refresh(); message('Usuário criado.');
} catch (e) { message(e.message,true); } finally { button.disabled = false; }
};
$('hideCredentials').onclick = () => { $('newCredentials').replaceChildren(); $('credentials').hidden = true; };
$('export').onclick = async () => {
$('export').disabled = true;
try { const blob = await (await api('/users/export')).blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='hotspot-usuarios.csv'; a.click(); setTimeout(()=>URL.revokeObjectURL(url),1000); message('CSV exportado sem senhas.'); }
catch(e) { message(e.message,true); } finally { $('export').disabled = false; }
};
+32 -6
View File
@@ -602,6 +602,7 @@
let toastTimer = null;
let selectedPlanId = null;
let mpDevice = null;
let checkoutBusy = false;
const $ = (id) => document.getElementById(id);
@@ -690,6 +691,9 @@
}
async function checkout(planId) {
if (checkoutBusy) return;
checkoutBusy = true;
$('payerNext').disabled = true;
try {
const payerName = $('payerName').value.trim();
const payerEmail = $('payerEmail').value.trim();
@@ -705,6 +709,7 @@
if (data.error) throw new Error(data.error);
currentPaymentId = data.paymentId;
sessionStorage.setItem('paymentId', currentPaymentId);
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
$('copiaCola').textContent = data.copiaCola || '';
@@ -715,6 +720,9 @@
pollTimer = setInterval(verify, 6000);
} catch (e) {
toast('Erro: ' + e.message);
} finally {
checkoutBusy = false;
$('payerNext').disabled = false;
}
}
@@ -730,6 +738,7 @@
btn.disabled = true;
try {
const res = await fetch('/api/status/' + encodeURIComponent(currentPaymentId));
if (!res.ok) throw new Error('Falha na consulta');
const data = await res.json();
if (data.status === 'paid' && data.voucher) {
clearInterval(pollTimer); pollTimer = null;
@@ -763,7 +772,7 @@
$('payerNext').addEventListener('click', () => checkout(selectedPlanId));
// ===== Login no hotspot (voucher) =====
const HS_LOGIN = 'http://10.10.10.1/login';
let HS_LOGIN = 'http://10.10.10.1/login';
function hsUrl(user, pass) {
return HS_LOGIN + '?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass);
@@ -777,13 +786,22 @@
const u = $('hsUser').value.trim();
const p = $('hsPass').value;
if (!u || !p) { toast('Informe usuário e senha'); return; }
window.location.href = hsUrl(u, p);
hotspotLogin(u, p);
});
$('hsAutoLogin').addEventListener('click', () => {
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
hotspotLogin($('vUser').textContent, $('vPass').textContent);
});
function hotspotLogin(user, pass, destination) {
const form = document.createElement('form');
form.method = 'POST'; form.action = HS_LOGIN;
for (const [name, value] of Object.entries({ username: user, password: pass, ...(destination ? { dst: destination } : {}) })) {
const field = document.createElement('input'); field.type = 'hidden'; field.name = name; field.value = value; form.append(field);
}
document.body.append(form); form.submit();
}
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
async function startFreeAccess() {
if (!mac) return;
@@ -796,7 +814,11 @@
body: JSON.stringify({ mac }),
});
const d = await res.json();
if (d.loginUrl) window.location.href = d.loginUrl;
if (!res.ok) { sessionStorage.removeItem('freeTried'); return; }
if (d.loginUrl) {
const target = new URL(d.loginUrl);
hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst'));
}
} catch { /* segue */ }
}
@@ -805,14 +827,18 @@
const res = await fetch('/api/config');
const d = await res.json();
if (d.ssid) $('ssidLabel').textContent = d.ssid;
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
} catch { /* usa padrao */ }
}
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
loadSiteConfig();
loadSiteConfig().then(startFreeAccess);
loadPlans();
startFreeAccess();
if (sessionStorage.getItem('paymentId')) {
currentPaymentId = sessionStorage.getItem('paymentId');
verify();
}
</script>
</body>
</html>
+92
View File
@@ -0,0 +1,92 @@
import express from 'express';
import { safeAsyncRoutes } from './http.js';
import crypto from 'node:crypto';
import config from './config.js';
import { rosCommand, createHotspotUser } from './ros.js';
import { getDb, saveDb, genCode } from './db.js';
import { equalSecret, rateLimit, validName, validUptime, csvCell } from './security.js';
export function adminAuth(req, res, next) {
if (!config.adminToken || config.adminToken.length < 32 || /^(dev-token|troque|replace|changeme|cole)/i.test(config.adminToken)) {
return res.status(503).json({ error: 'Configure ADMIN_TOKEN com pelo menos 32 caracteres aleatórios.' });
}
if (!equalSecret(req.headers['x-admin-token'], config.adminToken)) return res.status(401).json({ error: 'Token inválido.' });
next();
}
const rowObject = row => Object.fromEntries(row.filter(v => v.startsWith('=')).map(v => {
const i = v.indexOf('=', 1); return [v.slice(1, i), v.slice(i + 1)];
}));
const read = async words => (await rosCommand(words)).map(rowObject);
export async function hotspotUsers() {
const [users, active] = await Promise.all([
read(['/ip/hotspot/user/print']), read(['/ip/hotspot/active/print']),
]);
return users.filter(u => u.server === config.mikrotik.server || !u.server || u.server === 'all').map(u => ({
id: u['.id'], name: u.name, profile: u.profile || 'default', disabled: u.disabled === 'true',
uptime: u.uptime || '0s', limitUptime: u['limit-uptime'] || '0s',
bytesIn: Number(u['bytes-in'] || 0), bytesOut: Number(u['bytes-out'] || 0), comment: u.comment || '',
sessions: active.filter(a => a.user === u.name && a.server === config.mikrotik.server).map(a => ({
ip: a.address, mac: a['mac-address'], uptime: a.uptime,
})),
}));
}
function audit(action, target) {
const db = getDb();
db.audit = [...(db.audit || []), { id: crypto.randomUUID(), at: new Date().toISOString(), action, target }].slice(-1000);
saveDb();
}
export function adminRouter() {
const router = express.Router();
safeAsyncRoutes(router);
router.use(rateLimit(120, 60000), adminAuth);
router.get('/users', async (req, res) => res.json(await hotspotUsers()));
router.get('/profiles', async (req, res) => {
res.json((await read(['/ip/hotspot/user/profile/print'])).map(p => ({ name: p.name, rateLimit: p['rate-limit'] || '' })));
});
router.get('/audit', (req, res) => res.json((getDb().audit || []).slice(-100).reverse()));
router.get('/users/export', async (req, res) => {
const users = await hotspotUsers();
audit('export-users', String(users.length));
res.set('Content-Disposition', 'attachment; filename="hotspot-usuarios.csv"');
res.type('text/csv').send('\uFEFF' + [
['Usuário', 'Perfil', 'Bloqueado', 'Online', 'Tempo usado', 'Limite de uso', 'Bytes recebidos', 'Bytes enviados', 'Comentário'],
...users.map(u => [u.name, u.profile, u.disabled ? 'Sim' : 'Não', u.sessions.length ? 'Sim' : 'Não', u.uptime, u.limitUptime, u.bytesIn, u.bytesOut, u.comment]),
].map(row => row.map(csvCell).join(';')).join('\r\n'));
});
router.post('/users', async (req, res) => {
const { name, profile, uptime, comment = '' } = req.body || {};
const password = req.body?.password || genCode(12);
if (!validName(name) || !validName(profile) || !validUptime(uptime) ||
typeof password !== 'string' || password.length < 8 || password.length > 128 ||
typeof comment !== 'string' || comment.length > 200) return res.status(400).json({ error: 'Dados inválidos. Informe usuário, perfil, duração (ex.: 1h) e senha com pelo menos 8 caracteres.' });
const profiles = await read(['/ip/hotspot/user/profile/print', `?name=${profile}`]);
if (!profiles.length) return res.status(400).json({ error: 'Perfil inexistente no MikroTik.' });
const users = await read(['/ip/hotspot/user/print', `?name=${name}`]);
if (users.length) return res.status(409).json({ error: 'Usuário já existe.' });
await createHotspotUser(name, password, profile, uptime, 'pix:manual ' + comment);
audit('create-user', name);
res.status(201).json({ name, password });
});
router.patch('/users/:id', async (req, res) => {
if (!/^\*[0-9A-F]+$/i.test(req.params.id) || typeof req.body?.disabled !== 'boolean') return res.status(400).json({ error: 'Dados inválidos.' });
const user = (await hotspotUsers()).find(u => u.id === req.params.id);
if (!user) return res.status(404).json({ error: 'Usuário não encontrado neste hotspot.' });
const disabled = req.body.disabled;
await rosCommand(['/ip/hotspot/user/set', `=numbers=${user.id}`, `=disabled=${disabled ? 'yes' : 'no'}`]);
audit(disabled ? 'block-user' : 'unblock-user', user.name);
if (disabled) {
const [active, cookies] = await Promise.all([
read(['/ip/hotspot/active/print', `?user=${user.name}`]),
read(['/ip/hotspot/cookie/print', `?user=${user.name}`]),
]);
for (const a of active) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${a['.id']}`]);
for (const c of cookies) await rosCommand(['/ip/hotspot/cookie/remove', `=numbers=${c['.id']}`]);
}
res.json({ ok: true });
});
return router;
}
+13 -1
View File
@@ -6,6 +6,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const config = {
mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
mpWebhookSecret: process.env.MP_WEBHOOK_SECRET || '',
mpPublicKey: process.env.MP_PUBLIC_KEY || '',
mikrotik: {
host: process.env.MIKROTIK_HOST || '192.168.3.81',
@@ -20,8 +21,19 @@ const config = {
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',
adminToken: process.env.ADMIN_TOKEN || '',
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
};
for (const [name, value, max] of [
['PORT', config.port, 65535], ['MIKROTIK_PORT', config.mikrotik.port, 65535],
['FREE_ACCESS_SECONDS', config.freeAccessSeconds, 1800],
['FREE_ACCESS_COOLDOWN_SECONDS', config.freeAccessCooldownSeconds, 86400],
]) {
if (!Number.isInteger(value) || value < 1 || value > max) throw new Error(`${name} inválido`);
}
if (config.freeAccessCooldownSeconds < config.freeAccessSeconds) throw new Error('Cooldown deve ser maior ou igual ao acesso temporário');
if (!/^https?:$/.test(new URL(config.baseUrl).protocol)) throw new Error('BASE_URL inválida');
if (!/^(?:\d{1,3}\.){3}\d{1,3}$/.test(config.hotspotIp)) throw new Error('HOTSPOT_IP inválido');
export default config;
+9 -2
View File
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import config from './config.js';
import { validatePlans } from './security.js';
const DB_PATH = path.join(config.dataDir, 'db.json');
@@ -17,9 +18,15 @@ export function initDb() {
fs.mkdirSync(config.dataDir, { recursive: true });
if (fs.existsSync(DB_PATH)) {
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
if (!db.plans?.length) db.plans = structuredClone(DEFAULT_PLANS);
if (!Array.isArray(db.plans)) db.plans = structuredClone(DEFAULT_PLANS);
if (!db.payments) db.payments = [];
if (!validatePlans(db.plans) || !Array.isArray(db.payments)) throw new Error('Banco de dados inválido; restaure um backup.');
if (!db.tempAccess) db.tempAccess = [];
if (!Array.isArray(db.tempAccess)) throw new Error('Acessos temporários inválidos');
// Migrate old payments to a fixed plan snapshot before plans are edited.
for (const p of db.payments) {
if (!p.uptime) p.uptime = db.plans.find(plan => plan.id === p.planId)?.uptime;
}
} else {
db = { plans: structuredClone(DEFAULT_PLANS), payments: [], tempAccess: [] };
saveDb();
@@ -28,7 +35,7 @@ export function initDb() {
export function saveDb() {
const tmp = DB_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(db, null, 2));
fs.writeFileSync(tmp, JSON.stringify(db, null, 2), { mode: 0o600 });
fs.renameSync(tmp, DB_PATH);
}
+12
View File
@@ -0,0 +1,12 @@
// Express 4 does not forward rejected async handlers to error middleware.
export function safeAsyncRoutes(router) {
for (const method of ['get', 'post', 'patch', 'put', 'delete']) {
const original = router[method].bind(router);
router[method] = (path, ...handlers) => {
if (!handlers.length) return original(path);
return original(path, ...handlers.map(fn => (req, res, next) => {
try { Promise.resolve(fn(req, res, next)).catch(next); } catch (e) { next(e); }
}));
};
}
}
+86 -107
View File
@@ -1,68 +1,62 @@
import express from 'express';
import crypto from 'node:crypto';
import { paymentService } from './payments.js';
import { adminRouter, adminAuth } from './admin.js';
import { rateLimit, validMac, validatePlans } from './security.js';
import { safeAsyncRoutes } from './http.js';
import { verifyWebhook } from './webhook.js';
import path from 'node:path';
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, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js';
import { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
app.use(express.json());
export const app = express();
safeAsyncRoutes(app);
app.disable('x-powered-by');
if (process.env.TRUST_PROXY) app.set('trust proxy', process.env.TRUST_PROXY);
app.use((req, res, next) => {
res.set({ 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'X-Frame-Options': 'DENY' });
if (req.path.startsWith('/api/') || req.path.startsWith('/admin')) res.set('Cache-Control', 'no-store');
if (req.path.startsWith('/admin')) res.set('Content-Security-Policy', "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
next();
});
app.use(express.json({ limit: '16kb' }));
app.use('/api', rateLimit(300, 60000));
app.use('/api/checkout', rateLimit(10, 60000));
app.use('/api/access/start', rateLimit(10, 60000));
app.use('/api/admin', adminRouter());
app.get('/admin', (req, res) => res.sendFile(path.join(__dirname, '../public/admin.html')));
app.use(express.static(path.join(__dirname, '../public')));
initDb();
initMp();
async function fulfill(payment) {
if (payment.voucher) return payment;
const user = 'G' + genCode(6);
const pass = genCode(8);
const plan = getDb().plans.find((p) => p.id === payment.planId);
await createHotspotUser(user, pass, plan?.profile || payment.profile, plan?.uptime);
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;
}
async function checkPayment(payment) {
if (!payment.mpId || payment.status !== 'pending') return payment;
try {
const st = await getPaymentStatus(payment.mpId);
if (st === 'approved') return await fulfill(payment);
if (st === 'rejected' || st === 'cancelled' || st === 'expired') {
payment.status = st;
saveDb();
}
} catch (e) {
console.error('[MP] erro ao consultar:', e.message);
}
return payment;
}
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser });
// ===== Rotas =====
// ===== Internet temporaria para pagar (bypass do hotspot) =====
const accessLocks = new Set();
app.post('/api/access/start', async (req, res) => {
const { mac } = req.body || {};
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
if (!validMac(mac)) return res.status(400).json({ error: 'mac obrigatorio' });
if (accessLocks.has(mac)) return res.status(409).json({ error: 'Acesso em preparação. Tente novamente.' });
accessLocks.add(mac);
try {
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 });
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 });
}
const minutes = Math.max(1, Math.round(config.freeAccessSeconds / 60));
const minutes = Math.max(1, Math.ceil(config.freeAccessSeconds / 60));
const r = await allowPaymentAccess(mac, minutes);
const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1');
@@ -85,20 +79,22 @@ app.post('/api/access/start', async (req, res) => {
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 });
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
} finally {
accessLocks.delete(mac);
}
});
app.get('/api/access/status/:mac', async (req, res) => {
app.get('/api/access/status/:mac', adminAuth, async (req, res) => {
try {
res.json(await paymentAccessStatus(req.params.mac));
} catch (e) {
res.status(500).json({ error: e.message });
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
}
});
// ===== Reconciliacao manual (caso o webhook falhe) =====
app.post('/api/reconcile', async (req, res) => {
app.post('/api/reconcile', adminAuth, 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));
@@ -108,7 +104,7 @@ app.post('/api/reconcile', async (req, res) => {
});
app.get('/api/config', (req, res) => {
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds });
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds, hotspotIp: config.hotspotIp });
});
app.get('/api/plans', (req, res) => {
@@ -117,7 +113,10 @@ app.get('/api/plans', (req, res) => {
app.post('/api/checkout', async (req, res) => {
try {
const { planId, mac, payerName, payerEmail, payerCpf, deviceId } = req.body || {};
const { planId, payerName, payerEmail, payerCpf, deviceId } = req.body || {};
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
if (mac && !validMac(mac)) return res.status(400).json({ error: 'MAC inválido' });
if (typeof payerName !== 'string' || payerName.trim().length < 3 || payerName.length > 120 || typeof payerEmail !== 'string' || payerEmail.length > 254 || (deviceId && (typeof deviceId !== 'string' || deviceId.length > 200))) return res.status(400).json({ error: 'Dados inválidos' });
const plan = getDb().plans.find((p) => p.id === planId && p.active);
if (!plan) return res.status(400).json({ error: 'plano invalido' });
const email = String(payerEmail || '').trim();
@@ -133,9 +132,10 @@ app.post('/api/checkout', async (req, res) => {
const lastPurchase = hist.length ? hist[hist.length - 1].paidAt || hist[hist.length - 1].createdAt : null;
const payment = {
id: 'P' + Date.now() + genCode(4),
id: 'P' + crypto.randomUUID(),
planId: plan.id,
profile: plan.profile,
uptime: plan.uptime,
mac: mac || null,
price: plan.price,
status: 'pending',
@@ -173,45 +173,18 @@ app.post('/api/checkout', async (req, res) => {
});
} catch (e) {
console.error('[CHECKOUT]', e.message);
res.status(500).json({ error: e.message });
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
}
});
// ===== Webhook MP (IPN): confirma pagamento na hora =====
app.post('/api/mp/webhook', async (req, res) => {
res.sendStatus(200); // responde rápido para o MP não reenviar
try {
const d = req.body?.data || {};
const mpId = d.id || req.body?.id || req.query?.['data.id'] || req.query?.id;
const extRef = d.external_reference || req.body?.external_reference || req.query?.external_reference;
const pays = d.transactions?.payments || [];
const paidHint =
d.status === 'processed' ||
d.status_detail === 'accredited' ||
pays.some((p) => ['approved', 'processed'].includes(p.status));
const payment = getDb().payments.find(
(p) => (mpId && String(p.mpId) === String(mpId)) || (extRef && String(p.id) === String(extRef))
);
if (!payment) {
console.log('[WEBHOOK] nao localizado', mpId, extRef);
return;
}
if (paidHint && payment.status === 'pending') {
await checkPayment(payment);
if (payment.status === 'pending') {
// webhook diz pago: libera mesmo se a consulta ao MP falhar
await fulfill(payment);
saveDb();
}
} else {
await checkPayment(payment);
}
console.log(`[WEBHOOK] ${mpId || extRef} -> ${payment.status}`);
} catch (e) {
console.error('[WEBHOOK]', e.message);
}
if (!config.mpWebhookSecret) return res.status(503).json({ error: 'Webhook não configurado; polling continua ativo.' });
if (!verifyWebhook(req, config.mpWebhookSecret)) return res.sendStatus(401);
const mpId = req.query['data.id'] || req.body?.data?.id;
const payment = getDb().payments.find(p => String(p.mpId).toLowerCase() === String(mpId).toLowerCase());
if (payment) await checkPayment(payment);
res.sendStatus(200);
});
app.get('/api/status/:id', async (req, res) => {
@@ -226,19 +199,13 @@ app.get('/api/status/:id', async (req, res) => {
});
});
function adminAuth(req, res, next) {
const token = req.headers['x-admin-token'] || req.query.token;
if (token !== config.adminToken) return res.status(401).json({ error: 'token invalido' });
next();
}
app.get('/api/admin/payments', adminAuth, (req, res) => {
res.json(getDb().payments.slice(-100).reverse());
res.json(getDb().payments.slice(-100).reverse().map(({ qrCodeBase64, copiaCola, provisioning, ...payment }) => payment));
});
app.post('/api/admin/plans', adminAuth, (req, res) => {
const { plans } = req.body || {};
if (!Array.isArray(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
if (!validatePlans(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
getDb().plans = plans;
saveDb();
res.json({ ok: true });
@@ -255,13 +222,17 @@ app.post('/api/admin/payments/:id/cancel', adminAuth, async (req, res) => {
return res.status(400).json({ error: 'apenas pendentes podem ser cancelados' });
}
try {
await cancelOrder(payment.mpId);
await checkPayment(payment);
if (payment.status !== 'pending' || checks.has(payment.id)) return res.status(409).json({ error: 'Pagamento já processado.' });
const task = cancelOrder(payment.mpId);
checks.set(payment.id, task);
try { await task; } finally { checks.delete(payment.id); }
payment.status = 'cancelled';
saveDb();
console.log(`[CANCEL] order ${payment.mpId} cancelada`);
res.json({ ok: true, status: payment.status });
} catch (e) {
res.status(500).json({ error: e.message });
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
}
});
@@ -269,25 +240,33 @@ app.get('/api/health', async (req, res) => {
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
});
// ===== Polling: confirma pagamentos pendentes sozinho =====
let polling = false;
setInterval(async () => {
const pendings = getDb().payments.filter((p) => p.status === 'pending' && p.mpId);
for (const p of pendings) await checkPayment(p);
}, 15000);
// ===== Expira acessos temporarios de pagamento =====
if (polling) return;
polling = true;
try { for (const p of getDb().payments.filter(p => p.status === 'pending' && p.mpId)) await checkPayment(p); }
finally { polling = false; }
}, 15000).unref();
let cleaning = false;
setInterval(async () => {
if (cleaning) return;
cleaning = true;
try {
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);
for (const t of db.tempAccess || []) {
if (t.expiresAt <= Date.now() && !t.revoked && !accessLocks.has(t.mac)) {
try { await revokePaymentAccess(t.mac); t.revoked = true; saveDb(); }
catch (e) { console.error('[ACESSO]', e.message); }
}
}
db.tempAccess = (db.tempAccess || []).filter(t => !t.revoked || Date.parse(t.createdAt) + config.freeAccessCooldownSeconds * 1000 > Date.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}`);
} catch (e) { console.error('[LIMPEZA]', e.message); } finally { cleaning = false; }
}, 15000).unref();
app.use((err, req, res, next) => {
console.error('[HTTP]', err.message);
if (res.headersSent) return next(err);
const status = err.type === 'entity.too.large' ? 413 : err instanceof SyntaxError && 'body' in err ? 400 : 500;
res.status(status).json({ error: status === 400 ? 'JSON inválido' : status === 413 ? 'Solicitação muito grande' : 'Falha na operação. Consulte os logs do servidor.' });
});
if (process.env.NODE_ENV !== 'test') app.listen(config.port, '0.0.0.0', () => console.log('pix-hotspot em ' + config.baseUrl));
+31 -8
View File
@@ -125,7 +125,7 @@ export async function createPixPayment(opts) {
},
},
requestOptions: {
idempotencyKey: reference + '-' + Date.now(),
idempotencyKey: reference,
...(deviceId ? { meliSessionId: deviceId } : {}),
},
});
@@ -152,21 +152,44 @@ export async function cancelOrder(mpId) {
}
}
export async function getPaymentStatus(mpId) {
export function verifyPaidOrder(data, payment) {
if (!Number.isFinite(Number(data.total_paid_amount)) || !Number.isFinite(Number(data.total_amount))) throw new Error('Valor ausente na confirmação');
if (data.external_reference !== payment.id || Math.round(Number(data.total_amount) * 100) !== Math.round(payment.price * 100) ||
Math.round(Number(data.total_paid_amount) * 100) < Math.round(payment.price * 100)) {
throw new Error('Pagamento com referência ou valor divergente');
}
}
export function orderStatus(data) {
const pay = data.transactions?.payments?.[0] || {};
for (const item of [data, pay]) {
if (item.status_detail === 'expired' || item.status === 'expired') return 'expired';
if (['canceled', 'cancelled'].includes(item.status)) return 'cancelled';
if (['failed', 'rejected'].includes(item.status)) return 'rejected';
if (item.status === 'refunded') return 'refunded';
}
return data.status === 'processed' || ['approved', 'processed'].includes(pay.status) ? 'approved' : 'pending';
}
export async function getPaymentStatus(mpId, payment) {
// webhook pode notificar tanto a order (ORD...) quanto o pagamento (PAY...)
const isOrder = String(mpId).startsWith('ORD');
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' || ['approved', 'processed'].includes(pay.status)) 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 status = orderStatus(data);
if (status === 'approved') {
if (payment) verifyPaidOrder(data, payment);
return 'approved';
}
return status;
}
const data = await new Payment(getClient()).get({ id: mpId });
if (data.status === 'approved' && payment) {
verifyPaidOrder({ external_reference: data.external_reference, total_amount: data.transaction_amount, total_paid_amount: data.transaction_amount }, payment);
if (data.currency_id !== 'BRL') throw new Error('Moeda inesperada');
}
// payment: pending | approved | rejected | cancelled | expired ...
return data.status;
} catch (e) {
+45
View File
@@ -0,0 +1,45 @@
import { genCode } from './db.js';
// One application process owns the JSON database and these per-payment locks.
export function paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser }) {
const checks = new Map();
async function fulfill(payment) {
if (payment.voucher) return payment;
if (!payment.uptime) throw new Error('Pagamento sem limite de uso');
if (!payment.provisioning) {
payment.provisioning = { user: 'G' + genCode(12), pass: genCode(16) };
saveDb();
}
const { user, pass } = payment.provisioning;
const marker = 'pix:' + payment.id;
const rows = await rosCommand(['/ip/hotspot/user/print', '?name=' + user]);
if (rows.length) {
if (!rows.some(row => row.includes('=comment=' + marker))) throw new Error('Conflito no voucher');
} else await createHotspotUser(user, pass, payment.profile, payment.uptime, marker);
payment.voucher = { user, pass };
payment.status = 'paid';
payment.paidAt = new Date().toISOString();
delete payment.provisioning;
if (payment.mac) {
const temp = (getDb().tempAccess || []).find(t => t.mac === payment.mac);
if (temp) temp.expiresAt = Date.now();
}
saveDb();
return payment;
}
async function checkPayment(payment) {
if (!payment.mpId || payment.status !== 'pending') return payment;
if (checks.has(payment.id)) return checks.get(payment.id);
const task = (async () => {
try {
const st = await getPaymentStatus(payment.mpId, payment);
if (st === 'approved') return await fulfill(payment);
if (['rejected', 'cancelled', 'expired', 'refunded'].includes(st)) { payment.status = st; saveDb(); }
} catch (e) { console.error('[PAGAMENTO]', e.message); }
return payment;
})();
checks.set(payment.id, task);
try { return await task; } finally { checks.delete(payment.id); }
}
return { checkPayment, checks };
}
+22 -24
View File
@@ -1,5 +1,6 @@
import net from 'node:net';
import config from './config.js';
import crypto from 'node:crypto';
function packLen(n) {
if (n < 0x80) return Buffer.from([n]);
@@ -30,6 +31,7 @@ class Parser {
}
push(chunk) {
this.buf = Buffer.concat([this.buf, chunk]);
if (this.buf.length > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS excede o limite'; return; }
while (true) {
if (this.buf.length === 0) return;
const first = this.buf[0];
@@ -44,10 +46,11 @@ class Parser {
} else if ((first & 0xf0) === 0xe0) {
if (this.buf.length < 4) return;
len = ((first & 0x0f) << 24) | (this.buf[1] << 16) | (this.buf[2] << 8) | this.buf[3]; offset = 4;
} else {
} else if (first === 0xf0) {
if (this.buf.length < 5) return;
len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;
}
} else { this.error = 'Comprimento RouterOS inválido'; return; }
if (len < 0 || len > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS inválida'; return; }
if (this.buf.length < offset + len) return;
const data = this.buf.subarray(offset, offset + len);
this.buf = this.buf.subarray(offset + len);
@@ -70,11 +73,12 @@ class Parser {
if (attr === '!re') this.replies.push(words.slice(1));
else if (attr === '!done') this.done = true;
else if (attr === '!trap') this.error = words.slice(1).join(' ') || 'trap';
else if (attr === '!fatal') this.error = 'RouterOS encerrou a conexão';
else this.replies.push(words);
}
}
async function rosCommand(words, timeoutMs = 8000) {
export async function rosCommand(words, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
const socket = new net.Socket();
const parser = new Parser();
@@ -116,13 +120,14 @@ async function rosCommand(words, timeoutMs = 8000) {
});
}
export async function createHotspotUser(name, password, profile, uptime) {
export async function createHotspotUser(name, password, profile, uptime, comment = 'pix:manual') {
const words = [
'/ip/hotspot/user/add',
`=server=${config.mikrotik.server}`,
`=name=${name}`,
`=password=${password}`,
`=profile=${profile}`,
`=comment=${comment}`,
];
if (uptime) words.push(`=limit-uptime=${uptime}`);
await rosCommand(words);
@@ -154,17 +159,15 @@ async function hostAddressByMac(mac) {
}
function freeUserName(mac) {
return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').slice(-10).toUpperCase();
return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
}
async function removeUserByName(name) {
try {
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') {
@@ -181,7 +184,7 @@ async function ensureFreeProfile(rateLimit = '3M/3M') {
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);
throw new Error('Não foi possível preparar o perfil temporário', { cause: e });
}
}
@@ -198,9 +201,12 @@ async function removeActiveByMac(mac) {
// 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');
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}`]);
if (sessions.some(row => pickField(row, '=user=') !== freeUserName(mac))) throw new Error('Dispositivo já possui uma sessão autenticada');
await ensureFreeProfile();
const name = freeUserName(mac);
const pass = 'F' + Math.random().toString(36).slice(2, 9).toUpperCase();
const pass = crypto.randomBytes(16).toString('hex');
await removeUserByName(name);
await rosCommand([
'/ip/hotspot/user/add',
@@ -208,6 +214,7 @@ export async function allowPaymentAccess(mac, minutes = 10) {
`=name=${name}`,
`=password=${pass}`,
'=profile=pix-free',
`=mac-address=${mac}`,
`=limit-uptime=${minutes}m`,
]);
return { user: name, pass, mac };
@@ -234,22 +241,13 @@ export async function paymentAccessStatus(mac) {
export async function revokePaymentAccess(mac) {
if (!mac) return;
await removeActiveByMac(mac);
// Disconnect only the temporary account, never the paid voucher for this MAC.
const active = await rosCommand(['/ip/hotspot/active/print', `?user=${freeUserName(mac)}`]);
for (const row of active) {
const id = pickField(row, '=.id=');
if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);
}
await removeUserByName(freeUserName(mac));
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() {
+48
View File
@@ -0,0 +1,48 @@
import crypto from 'node:crypto';
export function equalSecret(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
const x = crypto.createHash('sha256').update(a).digest();
const y = crypto.createHash('sha256').update(b).digest();
return crypto.timingSafeEqual(x, y);
}
export const validMac = (mac) => typeof mac === 'string' && /^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac);
export const validUptime = (v) => typeof v === 'string' && v.length <= 40 && /^(?:\d+[wdhms])+$/.test(v) && /[1-9]/.test(v);
export const validName = (v) => typeof v === 'string' && /^[A-Za-z0-9_.@-]{1,64}$/.test(v);
export function validatePlans(plans) {
if (!Array.isArray(plans) || plans.length > 50) return false;
const ids = new Set();
return plans.every(p => {
if (!p || !validName(p.id) || ids.has(p.id) || !validName(p.profile) ||
typeof p.name !== 'string' || !p.name.trim() || p.name.length > 100 ||
typeof p.price !== 'number' || !Number.isFinite(p.price) || p.price < 0.01 || p.price > 10000 ||
Math.abs(p.price * 100 - Math.round(p.price * 100)) > 0.00001 ||
!validUptime(p.uptime) || typeof p.speed !== 'string' || p.speed.length > 40 || typeof p.active !== 'boolean') return false;
ids.add(p.id);
return true;
});
}
export function rateLimit(limit, windowMs) {
const buckets = new Map();
return (req, res, next) => {
const now = Date.now();
for (const [key, value] of buckets) if (value.until <= now) buckets.delete(key);
const key = req.ip;
const bucket = buckets.get(key) || { count: 0, until: now + windowMs };
buckets.set(key, bucket);
if (++bucket.count > limit) {
res.set('Retry-After', String(Math.ceil((bucket.until - now) / 1000)));
return res.status(429).json({ error: 'Muitas solicitações. Tente novamente em instantes.' });
}
next();
};
}
export function csvCell(value) {
let text = String(value ?? '');
if (/^[\s]*[=+@-]/.test(text)) text = "'" + text;
return '"' + text.replaceAll('"', '""') + '"';
}
+14
View File
@@ -0,0 +1,14 @@
import crypto from 'node:crypto';
import { equalSecret } from './security.js';
export function verifyWebhook(req, secret) {
const parts = Object.fromEntries(String(req.headers['x-signature'] || '').split(',').map(p => p.trim().split('=')));
const id = req.query['data.id'] || req.body?.data?.id;
const requestId = req.headers['x-request-id'];
if (!secret || typeof id !== 'string' || typeof requestId !== 'string' || !/^\d+$/.test(parts.ts || '') || !/^[a-f0-9]{64}$/i.test(parts.v1 || '')) return false;
const timestamp = Number(parts.ts) * (parts.ts.length <= 10 ? 1000 : 1);
if (Math.abs(Date.now() - timestamp) > 5 * 60 * 1000) return false;
const manifest = `id:${id.toLowerCase()};request-id:${requestId};ts:${parts.ts};`;
const signature = crypto.createHmac('sha256', secret).update(manifest).digest('hex');
return equalSecret(signature, parts.v1.toLowerCase());
}
+70
View File
@@ -0,0 +1,70 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import net from 'node:net';
test('admin API authenticates, creates, lists, blocks, disconnects and exports with a local RouterOS simulator', async t => {
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'}];
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])]);
}
const ros=net.createServer(socket=>{
let buf=Buffer.alloc(0),words=[];
socket.on('data',chunk=>{
buf=Buffer.concat([buf,chunk]);
while(buf.length){
let n=buf[0],off=1;if(n&128){if(buf.length<2)return;n=((n&63)<<8)|buf[1];off=2;}
if(buf.length<off+n)return;
if(n){words.push(buf.subarray(off,off+n).toString());buf=buf.subarray(off+n);continue;}
buf=buf.subarray(off);const cmd=words;words=[];
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;}
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'}];
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/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);
for(const row of rows) socket.write(encode(['!re',...Object.entries(row).map(([k,v])=>'='+k+'='+v)]));
socket.write(encode(['!done']));
}
});
});
await new Promise(r=>ros.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>ros.close(r)));
process.env.NODE_ENV='test';process.env.MIKROTIK_HOST='127.0.0.1';process.env.MIKROTIK_PORT=String(ros.address().port);process.env.ADMIN_TOKEN='a'.repeat(48);
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'hotspot-test-'));process.env.DATA_DIR=dataDir;
t.after(()=>fs.rmSync(dataDir,{recursive:true,force:true}));
const { app }=await import('../src/index.js');
const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r));t.after(()=>new Promise(r=>server.close(r)));
const base='http://127.0.0.1:'+server.address().port;
const request=(url,method='GET',body)=>fetch(base+url,{method,headers:{'x-admin-token':process.env.ADMIN_TOKEN,'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
assert.equal((await fetch(base+'/api/admin/users')).status,401);
const { default: config } = await import('../src/config.js');
const originalToken = config.adminToken;
config.adminToken = 'replace-with-at-least-32-random-characters';
assert.equal((await request('/api/admin/users')).status,503);
config.adminToken = originalToken;
assert.equal((await fetch(base+'/api/admin/users?token='+process.env.ADMIN_TOKEN)).status,401);
let res=await request('/api/admin/users');assert.equal(res.status,200);let list=await res.json();assert.equal(list[0].sessions.length,1);assert.equal('password' in list[0],false);
res=await request('/api/admin/users','POST',{name:'new-user',profile:'pix-1h',uptime:'1h'});assert.equal(res.status,201);assert.ok((await res.json()).password.length>=8);
assert.equal((await request('/api/admin/users','POST',{name:'new-user',profile:'pix-1h',uptime:'1h'})).status,409);
assert.equal((await request('/api/admin/users/*1','PATCH',{disabled:true})).status,200);assert.equal(users[0].disabled,'true');assert.equal(active.length,0);assert.equal(cookies.length,0);
assert.equal((await request('/api/admin/users/*1','PATCH',{disabled:false})).status,200);assert.equal(users[0].disabled,'false');
res=await request('/api/admin/users/export');assert.equal(res.status,200);const csv=await res.text();assert.ok(csv.includes("'=FORMULA()"));assert.ok(!csv.includes('password'));
assert.equal((await request('/api/admin/users/*F','PATCH',{disabled:true})).status,404);
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);
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'));
});
+56
View File
@@ -0,0 +1,56 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { validMac, validatePlans, csvCell } from '../src/security.js';
import { verifyWebhook } from '../src/webhook.js';
import { verifyPaidOrder, orderStatus } from '../src/mp.js';
import { paymentService } from '../src/payments.js';
test('webhook accepts signed notifications and rejects forged, expired and modified IDs', () => {
const ts = String(Date.now()), secret = 'secret', id = 'ORD123';
const v1 = crypto.createHmac('sha256', secret).update(`id:${id.toLowerCase()};request-id:req1;ts:${ts};`).digest('hex');
const req = { query: { 'data.id': id }, headers: { 'x-request-id': 'req1', 'x-signature': `ts=${ts},v1=${v1}` } };
assert.equal(verifyWebhook(req, secret), true);
assert.equal(verifyWebhook(req, 'wrong'), false);
req.query['data.id'] = 'ORD456'; assert.equal(verifyWebhook(req, secret), false);
req.query['data.id'] = id; req.headers['x-signature'] = `ts=1,v1=${v1}`;
assert.equal(verifyWebhook(req, secret), false);
});
test('only the expected reference and fully paid amount are accepted', () => {
const payment = { id: 'P1', price: 3 };
const data = { external_reference: 'P1', total_amount: '3.00', total_paid_amount: '3.00' };
assert.doesNotThrow(() => verifyPaidOrder(data, payment));
for (const patch of [{ external_reference: 'P2' }, { total_amount: '0.01' }, { total_paid_amount: '0.01' }, { total_paid_amount: undefined }, { total_paid_amount: 'NaN' }]) assert.throws(() => verifyPaidOrder({ ...data, ...patch }, payment));
});
test('validates plan changes and neutralizes CSV formulas', () => {
const p = { id:'p1',name:'Hora',price:3,profile:'pix-1h',uptime:'1h',speed:'5M/1M',active:true };
assert.equal(validatePlans([p]),true);
for (const patch of [{price:-1},{price:'3'},{price:NaN},{price:3.001},{uptime:'0h'},{profile:'bad\nvalue'}]) assert.equal(validatePlans([{...p,...patch}]),false);
assert.equal(validatePlans([p,p]),false);
assert.equal(validMac('AA:BB:CC:DD:EE:FF'),true); assert.equal(validMac('anything'),false);
assert.equal(csvCell('=HYPERLINK("bad")'),'"\'=HYPERLINK(""bad"")"');
});
test('normalizes Orders API cancellations, failures, expirations and refunds', () => {
for (const [status, expected] of [['canceled','cancelled'],['failed','rejected'],['refunded','refunded'],['processed','approved'],['action_required','pending']]) assert.equal(orderStatus({status}),expected);
assert.equal(orderStatus({status:'canceled',status_detail:'expired'}),'expired');
assert.equal(orderStatus({status:'processed',transactions:{payments:[{status:'refunded'}]}}),'refunded');
});
test('simultaneous confirmations issue only one voucher', async () => {
let creates=0, queries=0;
const payment={id:'P1',mpId:'ORD1',status:'pending',profile:'pix-1h',uptime:'1h'};
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{queries++;await new Promise(r=>setTimeout(r,10));return 'approved';},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
await Promise.all(Array.from({length:10},()=>svc.checkPayment(payment)));
assert.equal(queries,1);assert.equal(creates,1);assert.equal(payment.status,'paid');
});
test('RouterOS timeout retries reuse the persisted username without duplicating the voucher', async () => {
let created=null, calls=0;
const payment={id:'P2',mpId:'ORD2',status:'pending',profile:'pix-1h',uptime:'1h'};
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=> 'approved',rosCommand:async()=>created ? [['=comment=pix:P2']] : [],createHotspotUser:async name=>{created=name;calls++;throw new Error('timeout after create');}});
await svc.checkPayment(payment);assert.equal(payment.status,'pending');assert.ok(payment.provisioning);
await svc.checkPayment(payment);assert.equal(payment.status,'paid');assert.equal(payment.voucher.user,created);assert.equal(calls,1);
});
test('unconfirmed payments never provision users', async () => {
let creates=0;
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{throw new Error('MP unavailable');},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
const p={id:'P3',mpId:'ORD3',status:'pending'};await svc.checkPayment(p);assert.equal(creates,0);assert.equal(p.status,'pending');
});