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

+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());
}