feat: hotspot PIX MikroTik + backend Docker + CI Gitea Actions
build-image / build-push (push) Failing after 4m36s
build-image / build-push (push) Failing after 4m36s
This commit is contained in:
commit
de9bd4ae0b
15 files changed
+1720
No files matched your search
@@ -0,0 +1,22 @@
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const config = {
|
||||
mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
|
||||
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
|
||||
mikrotik: {
|
||||
host: process.env.MIKROTIK_HOST || '192.168.3.81',
|
||||
port: parseInt(process.env.MIKROTIK_PORT || '8728', 10),
|
||||
user: process.env.MIKROTIK_USER || 'admin',
|
||||
password: process.env.MIKROTIK_PASSWORD || '',
|
||||
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
||||
},
|
||||
port: parseInt(process.env.PORT || '3000', 10),
|
||||
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'),
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,44 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import config from './config.js';
|
||||
|
||||
const DB_PATH = path.join(config.dataDir, 'db.json');
|
||||
|
||||
const DEFAULT_PLANS = [
|
||||
{ id: 'plano-1h', name: '1 Hora', price: 3.00, profile: 'pix-1h', uptime: '1h', speed: '5M/1M', active: true },
|
||||
{ id: 'plano-24h', name: '24 Horas', price: 5.00, profile: 'pix-24h', uptime: '1d', speed: '8M/2M', active: true },
|
||||
{ id: 'plano-7d', name: '7 Dias', price: 15.00, profile: 'pix-7d', uptime: '1w', speed: '10M/3M', active: true },
|
||||
];
|
||||
|
||||
let db = { plans: [], payments: [] };
|
||||
|
||||
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 (!db.payments) db.payments = [];
|
||||
} else {
|
||||
db = { plans: structuredClone(DEFAULT_PLANS), payments: [] };
|
||||
saveDb();
|
||||
}
|
||||
}
|
||||
|
||||
export function saveDb() {
|
||||
const tmp = DB_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(db, null, 2));
|
||||
fs.renameSync(tmp, DB_PATH);
|
||||
}
|
||||
|
||||
export function getDb() {
|
||||
return db;
|
||||
}
|
||||
|
||||
export function genCode(len = 8) {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const bytes = crypto.randomBytes(len);
|
||||
let out = '';
|
||||
for (let i = 0; i < len; i++) out += chars[bytes[i] % chars.length];
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import express from 'express';
|
||||
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 } from './mp.js';
|
||||
import { createHotspotUser } from './ros.js';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
// ===== Rotas =====
|
||||
|
||||
app.get('/api/plans', (req, res) => {
|
||||
res.json(getDb().plans.filter((p) => p.active));
|
||||
});
|
||||
|
||||
app.post('/api/checkout', async (req, res) => {
|
||||
try {
|
||||
const { planId, mac } = req.body || {};
|
||||
const plan = getDb().plans.find((p) => p.id === planId && p.active);
|
||||
if (!plan) return res.status(400).json({ error: 'plano invalido' });
|
||||
|
||||
const payment = {
|
||||
id: 'P' + Date.now() + genCode(4),
|
||||
planId: plan.id,
|
||||
profile: plan.profile,
|
||||
mac: mac || null,
|
||||
price: plan.price,
|
||||
status: 'pending',
|
||||
mpId: null,
|
||||
voucher: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const pix = await createPixPayment(plan.price, payment.id, `WiFi ${plan.name}`);
|
||||
payment.mpId = pix.mpId;
|
||||
payment.qrCodeBase64 = pix.qrCodeBase64;
|
||||
payment.copiaCola = pix.copiaCola;
|
||||
getDb().payments.push(payment);
|
||||
saveDb();
|
||||
|
||||
res.json({
|
||||
paymentId: payment.id,
|
||||
qrCodeBase64: pix.qrCodeBase64,
|
||||
copiaCola: pix.copiaCola,
|
||||
price: plan.price,
|
||||
planName: plan.name,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[CHECKOUT]', e.message);
|
||||
res.status(500).json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
voucher: payment.voucher,
|
||||
planName: getDb().plans.find((p) => p.id === payment.planId)?.name,
|
||||
});
|
||||
});
|
||||
|
||||
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());
|
||||
});
|
||||
|
||||
app.post('/api/admin/plans', adminAuth, (req, res) => {
|
||||
const { plans } = req.body || {};
|
||||
if (!Array.isArray(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
|
||||
getDb().plans = plans;
|
||||
saveDb();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
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 =====
|
||||
setInterval(async () => {
|
||||
const pendings = getDb().payments.filter((p) => p.status === 'pending' && p.mpId);
|
||||
for (const p of pendings) await checkPayment(p);
|
||||
}, 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}`);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { MercadoPagoConfig, Payment } from 'mercadopago';
|
||||
import config from './config.js';
|
||||
|
||||
let paymentApi = null;
|
||||
|
||||
export function initMp() {
|
||||
if (!config.mpAccessToken || config.mpAccessToken.includes('COLE_SEU')) {
|
||||
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao');
|
||||
return;
|
||||
}
|
||||
const client = new MercadoPagoConfig({ accessToken: config.mpAccessToken });
|
||||
paymentApi = new Payment(client);
|
||||
}
|
||||
|
||||
export async function createPixPayment(amount, reference, description) {
|
||||
if (!paymentApi) throw new Error('Mercado Pago nao configurado');
|
||||
const result = await paymentApi.create({
|
||||
body: {
|
||||
transaction_amount: amount,
|
||||
payment_method_id: 'pix',
|
||||
external_reference: reference,
|
||||
description,
|
||||
payer: { email: '[email protected]' },
|
||||
},
|
||||
});
|
||||
const tx = result.point_of_interaction?.transaction_data;
|
||||
if (!tx) throw new Error('Resposta do MP sem dados PIX');
|
||||
return {
|
||||
mpId: result.id,
|
||||
qrCodeBase64: tx.qr_code_base64 || null,
|
||||
copiaCola: tx.qr_code || tx.ticket_url || '',
|
||||
status: result.status,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPaymentStatus(mpId) {
|
||||
if (!paymentApi) throw new Error('Mercado Pago nao configurado');
|
||||
const result = await paymentApi.get({ id: mpId });
|
||||
return result.status; // pending | approved | rejected | cancelled | ...
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import net from 'node:net';
|
||||
import config from './config.js';
|
||||
|
||||
function packLen(n) {
|
||||
if (n < 0x80) return Buffer.from([n]);
|
||||
if (n < 0x4000) return Buffer.from([0x80 | (n >> 8), n & 0xff]);
|
||||
if (n < 0x200000) return Buffer.from([0xc0 | (n >> 16), (n >> 8) & 0xff, n & 0xff]);
|
||||
if (n < 0x10000000) return Buffer.from([0xe0 | (n >> 24), (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);
|
||||
return Buffer.from([0xf0, (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);
|
||||
}
|
||||
|
||||
function encodeSentence(words) {
|
||||
const parts = [];
|
||||
for (const w of words) {
|
||||
const buf = Buffer.from(String(w), 'utf8');
|
||||
parts.push(packLen(buf.length), buf, Buffer.from([0]));
|
||||
}
|
||||
parts.push(Buffer.from([0]));
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
class Parser {
|
||||
constructor() {
|
||||
this.buf = Buffer.alloc(0);
|
||||
this.words = [];
|
||||
this.sentence = [];
|
||||
this.done = false;
|
||||
this.error = null;
|
||||
this.replies = [];
|
||||
}
|
||||
push(chunk) {
|
||||
this.buf = Buffer.concat([this.buf, chunk]);
|
||||
while (true) {
|
||||
if (this.buf.length === 0) return;
|
||||
const first = this.buf[0];
|
||||
let len, offset;
|
||||
if ((first & 0x80) === 0) { len = first; offset = 1; }
|
||||
else if ((first & 0xc0) === 0x80) {
|
||||
if (this.buf.length < 2) return;
|
||||
len = ((first & 0x3f) << 8) | this.buf[1]; offset = 2;
|
||||
} else if ((first & 0xe0) === 0xc0) {
|
||||
if (this.buf.length < 3) return;
|
||||
len = ((first & 0x1f) << 16) | (this.buf[1] << 8) | this.buf[2]; offset = 3;
|
||||
} 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 {
|
||||
if (this.buf.length < 5) return;
|
||||
len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;
|
||||
}
|
||||
if (this.buf.length < offset + len) return;
|
||||
const data = this.buf.subarray(offset, offset + len);
|
||||
this.buf = this.buf.subarray(offset + len);
|
||||
if (len === 0) {
|
||||
if (this.sentence.length > 0) {
|
||||
this.handleSentence(this.sentence);
|
||||
this.sentence = [];
|
||||
} else if (this.words.length > 0) {
|
||||
this.handleSentence(this.words);
|
||||
this.words = [];
|
||||
}
|
||||
if (this.done || this.error) return;
|
||||
} else {
|
||||
this.words.push(data.toString('utf8'));
|
||||
}
|
||||
}
|
||||
}
|
||||
handleSentence(words) {
|
||||
const attr = words[0];
|
||||
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 this.replies.push(words);
|
||||
}
|
||||
}
|
||||
|
||||
async function rosCommand(words, timeoutMs = 8000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new net.Socket();
|
||||
const parser = new Parser();
|
||||
let settled = false;
|
||||
const finish = (err, val) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
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'));
|
||||
});
|
||||
socket.connect(config.mikrotik.port, config.mikrotik.host, () => {
|
||||
socket.write(encodeSentence(['/login', `=name=${config.mikrotik.user}`, `=password=${config.mikrotik.password}`]));
|
||||
const onLogin = (chunk) => {
|
||||
parser.push(chunk);
|
||||
if (parser.error) { socket.off('data', onLogin); return finish(new Error(parser.error)); }
|
||||
if (parser.done) {
|
||||
socket.off('data', onLogin);
|
||||
// login ok - recria parser e envia comando
|
||||
const p2 = new Parser();
|
||||
const onData2 = (c2) => {
|
||||
p2.push(c2);
|
||||
if (p2.error) finish(new Error(p2.error));
|
||||
else if (p2.done) finish(null, p2.replies);
|
||||
};
|
||||
socket.on('data', onData2);
|
||||
socket.write(encodeSentence(words));
|
||||
} else if (parser.replies.length && parser.replies.some(r => r.some(w => w.startsWith('=ret=')))) {
|
||||
finish(new Error('RouterOS antigo (<6.43): use login simples - atualize o RouterOS'));
|
||||
}
|
||||
};
|
||||
socket.on('data', onLogin);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function createHotspotUser(name, password, profile, uptime) {
|
||||
const words = [
|
||||
'/ip/hotspot/user/add',
|
||||
`=server=${config.mikrotik.server}`,
|
||||
`=name=${name}`,
|
||||
`=password=${password}`,
|
||||
`=profile=${profile}`,
|
||||
];
|
||||
if (uptime) words.push(`=limit-uptime=${uptime}`);
|
||||
await rosCommand(words);
|
||||
}
|
||||
|
||||
export async function mikrotikPing() {
|
||||
const replies = await rosCommand(['/system/identity/print']);
|
||||
return replies?.[0]?.find((w) => w.startsWith('=name='))?.slice(6) || 'ok';
|
||||
}
|
||||
Reference in new issue
Block a user