fix(ros): remove listener que abortava a API apos o login; liberacao de 2min via login automatico
build-image / build-push (push) Successful in 1m47s

This commit is contained in:
jfeng committed 2026-10-22 09:55:28 -03:00
1 parent 8e65d092e2
commit fb3135d18f
4 files changed
+87 -36

No files matched your search

+3 -1
View File
@@ -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'),
+21 -3
View File
@@ -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 });
+56 -21
View File
@@ -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 || []) {