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