Files
HotSpot/backend/src/db.js
T
jfeng ebb2d1d792
build-image / build-push (push) Failing after 1m36s
feat: add hotspot admin panel and harden payment provisioning
2026-10-22 14:01:08 +00:00

53 lines
2.0 KiB
JavaScript

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');
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: [], tempAccess: [] };
export function initDb() {
fs.mkdirSync(config.dataDir, { recursive: true });
if (fs.existsSync(DB_PATH)) {
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
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();
}
}
export function saveDb() {
const tmp = DB_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(db, null, 2), { mode: 0o600 });
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;
}