feat: add hotspot admin panel and harden payment provisioning
build-image / build-push (push) Failing after 1m36s
build-image / build-push (push) Failing after 1m36s
This commit is contained in:
1 parent
fb3135d18f
commit
ebb2d1d792
25 files changed
+832
-686
No files matched your search
+86
-107
@@ -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));
|
||||
Reference in new issue
Block a user