64 lines
2.2 KiB
TypeScript
64 lines
2.2 KiB
TypeScript
/**
|
||
* Configuración de Seguridad
|
||
* Valida variables de entorno críticas al startup
|
||
*/
|
||
|
||
import dotenv from 'dotenv';
|
||
dotenv.config();
|
||
|
||
interface SecurityConfig {
|
||
JWT_SECRET: string;
|
||
JWT_EXPIRES_IN: string;
|
||
WEBHOOK_SECRET: string;
|
||
}
|
||
|
||
/**
|
||
* Validar configuración de seguridad
|
||
* Si alguna variable crítica falta, la app no arranca
|
||
*/
|
||
export function validateSecurityConfig(): SecurityConfig {
|
||
const errors: string[] = [];
|
||
|
||
// JWT_SECRET es crítico - debe existir y no ser el valor por defecto
|
||
const JWT_SECRET = process.env.JWT_SECRET;
|
||
if (!JWT_SECRET) {
|
||
errors.push('JWT_SECRET no está configurado en .env');
|
||
console.error('❌ CRÍTICO: JWT_SECRET no configurado');
|
||
console.error(' Generar con: openssl rand -base64 32');
|
||
} else if (JWT_SECRET === 'emerges-tes-secret-key-change-in-production') {
|
||
errors.push('JWT_SECRET está usando el valor por defecto inseguro');
|
||
console.error('❌ CRÍTICO: JWT_SECRET usa valor por defecto inseguro');
|
||
console.error(' Generar un secret seguro con: openssl rand -base64 32');
|
||
console.error(' Y actualizarlo en .env');
|
||
} else if (JWT_SECRET.length < 32) {
|
||
errors.push('JWT_SECRET debe tener al menos 32 caracteres');
|
||
console.error('❌ CRÍTICO: JWT_SECRET demasiado corto (mínimo 32 caracteres)');
|
||
}
|
||
|
||
// WEBHOOK_SECRET es crítico en producción
|
||
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
|
||
if (process.env.NODE_ENV === 'production' && !WEBHOOK_SECRET) {
|
||
errors.push('WEBHOOK_SECRET no configurado en producción');
|
||
console.error('❌ CRÍTICO: WEBHOOK_SECRET no configurado en producción');
|
||
}
|
||
|
||
// Si hay errores críticos, salir
|
||
if (errors.length > 0) {
|
||
console.error('\n🚨 ERRORES DE SEGURIDAD ENCONTRADOS:');
|
||
errors.forEach((error, index) => {
|
||
console.error(` ${index + 1}. ${error}`);
|
||
});
|
||
console.error('\n⚠️ La aplicación no puede iniciarse con estos errores de seguridad.\n');
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log('✅ Variables de seguridad validadas correctamente');
|
||
|
||
return {
|
||
JWT_SECRET: JWT_SECRET || '',
|
||
JWT_EXPIRES_IN: process.env.JWT_EXPIRES_IN || '24h',
|
||
WEBHOOK_SECRET: WEBHOOK_SECRET || '',
|
||
};
|
||
}
|
||
|