275 lines
11 KiB
JavaScript
275 lines
11 KiB
JavaScript
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 { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
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();
|
|
// Check volume write access before accepting checkouts or creating PIX orders.
|
|
saveDb();
|
|
initMp();
|
|
|
|
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 = 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 && 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.ceil(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,
|
|
user: r.user,
|
|
loginUrl,
|
|
createdAt: new Date(now).toISOString(),
|
|
expiresAt: now + config.freeAccessSeconds * 1000,
|
|
});
|
|
saveDb();
|
|
|
|
res.json({ ok: true, seconds: config.freeAccessSeconds, 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.' });
|
|
} finally {
|
|
accessLocks.delete(mac);
|
|
}
|
|
});
|
|
|
|
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: 'Falha na operação. Consulte os logs do servidor.' });
|
|
}
|
|
});
|
|
|
|
// ===== Reconciliacao manual (caso o webhook falhe) =====
|
|
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));
|
|
if (!payment) return res.status(404).json({ error: 'pedido nao encontrado' });
|
|
await checkPayment(payment);
|
|
res.json({ status: payment.status, voucher: payment.voucher, orderId: payment.mpId });
|
|
});
|
|
|
|
app.get('/api/config', (req, res) => {
|
|
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds, hotspotIp: config.hotspotIp });
|
|
});
|
|
|
|
app.get('/api/plans', (req, res) => {
|
|
res.json(getDb().plans.filter((p) => p.active));
|
|
});
|
|
|
|
app.post('/api/checkout', async (req, res) => {
|
|
try {
|
|
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();
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) {
|
|
return res.status(400).json({ error: 'email invalido' });
|
|
}
|
|
if (payerCpf && !validCpf(payerCpf)) return res.status(400).json({ error: 'CPF invalido' });
|
|
|
|
// historico do comprador (primeira compra / ultima compra)
|
|
const hist = getDb().payments.filter((p) => p.mac && p.mac === mac && p.status === 'paid');
|
|
const firstPurchase = hist.length === 0;
|
|
const registrationDate = (hist[0] && hist[0].createdAt) || new Date().toISOString();
|
|
const lastPurchase = hist.length ? hist[hist.length - 1].paidAt || hist[hist.length - 1].createdAt : null;
|
|
|
|
const payment = {
|
|
id: 'P' + crypto.randomUUID(),
|
|
planId: plan.id,
|
|
profile: plan.profile,
|
|
uptime: plan.uptime,
|
|
mac: mac || null,
|
|
price: plan.price,
|
|
status: 'pending',
|
|
mpId: null,
|
|
voucher: null,
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
|
|
const pix = await createPixPayment({
|
|
amount: plan.price,
|
|
reference: payment.id,
|
|
planId: plan.id,
|
|
planName: plan.name,
|
|
payerName,
|
|
payerEmail: email,
|
|
payerCpf,
|
|
firstPurchase,
|
|
registrationDate,
|
|
lastPurchase,
|
|
deviceId,
|
|
});
|
|
payment.mpId = pix.mpId;
|
|
payment.qrCodeBase64 = pix.qrCodeBase64;
|
|
payment.copiaCola = pix.copiaCola;
|
|
getDb().payments.push(payment);
|
|
saveDb();
|
|
|
|
res.json({
|
|
paymentId: payment.id,
|
|
orderId: pix.mpId,
|
|
qrCodeBase64: pix.qrCodeBase64,
|
|
copiaCola: pix.copiaCola,
|
|
price: plan.price,
|
|
planName: plan.name,
|
|
});
|
|
} catch (e) {
|
|
console.error('[CHECKOUT]', 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) => {
|
|
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) => {
|
|
const payment = getDb().payments.find((p) => p.id === req.params.id);
|
|
if (!payment) return res.status(404).json({ error: 'nao encontrado' });
|
|
await checkPayment(payment);
|
|
res.json({
|
|
status: payment.status,
|
|
orderId: payment.mpId,
|
|
voucher: payment.voucher,
|
|
planName: getDb().plans.find((p) => p.id === payment.planId)?.name,
|
|
});
|
|
});
|
|
|
|
app.get('/api/admin/payments', adminAuth, (req, res) => {
|
|
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 (!validatePlans(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
|
|
getDb().plans = plans;
|
|
saveDb();
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.get('/api/mp/public-key', (req, res) => {
|
|
res.json({ publicKey: config.mpPublicKey || '' });
|
|
});
|
|
|
|
app.post('/api/admin/payments/:id/cancel', adminAuth, async (req, res) => {
|
|
const payment = getDb().payments.find((p) => p.id === req.params.id);
|
|
if (!payment) return res.status(404).json({ error: 'nao encontrado' });
|
|
if (!payment.mpId || payment.status !== 'pending') {
|
|
return res.status(400).json({ error: 'apenas pendentes podem ser cancelados' });
|
|
}
|
|
try {
|
|
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: 'Falha na operação. Consulte os logs do servidor.' });
|
|
}
|
|
});
|
|
|
|
app.get('/api/health', async (req, res) => {
|
|
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
|
|
});
|
|
|
|
let polling = false;
|
|
setInterval(async () => {
|
|
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();
|
|
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();
|
|
} 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));
|