fix: confirm temporary hotspot login and show payment access countdown
build-image / build-push (push) Successful in 2m48s

This commit is contained in:
jfeng committed 2026-10-22 15:35:19 +00:00
1 parent bba6dcd37e
commit 0c01e5d88b
5 files changed
+105 -23

No files matched your search

+16 -8
View File
@@ -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.' });
+20 -4
View File
@@ -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;