// SECURE - Proper environment variable handling
const dotenv = require('dotenv');
const crypto = require('crypto');
class ConfigManager {
constructor() {
this.loadEnvironment();
this.validateConfig();
}
loadEnvironment() {
// Load .env file only in development
if (process.env.NODE_ENV !== 'production') {
const result = dotenv.config();
if (result.error) {
console.warn('Warning: .env file not found');
}
}
// In production, variables should be injected by the environment
// (e.g., Docker secrets, Kubernetes secrets, PaaS config vars)
}
validateConfig() {
const required = [
'DATABASE_URL',
'JWT_SECRET',
'ENCRYPTION_KEY'
];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
// Validate format and strength
this.validateDatabaseUrl();
this.validateSecrets();
}
validateDatabaseUrl() {
const dbUrl = process.env.DATABASE_URL;
try {
const url = new URL(dbUrl);
// Example strength check (adjust as needed)
if (!url.password || url.password.length < 12) {
console.warn('Warning: Database password seems weak');
}
} catch (error) {
throw new Error(`Invalid DATABASE_URL format: ${error.message}`);
}
}
validateSecrets() {
// Check JWT secret strength
const jwtSecret = process.env.JWT_SECRET;
if (!jwtSecret || jwtSecret.length < 32) {
throw new Error('JWT_SECRET must be at least 32 characters');
}
// Check encryption key format (e.g., 64 hex chars for AES-256)
const encKey = process.env.ENCRYPTION_KEY;
if (!encKey || !/^[0-9a-fA-F]{64}$/.test(encKey)) {
throw new Error('ENCRYPTION_KEY must be 64 hex characters (32 bytes)');
}
}
getConfig() {
// Return structured config, ensuring secrets aren't accidentally logged
return {
database: {
url: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production'
},
jwt: {
secret: process.env.JWT_SECRET,
expiresIn: '15m' // Keep short
},
encryption: {
key: Buffer.from(process.env.ENCRYPTION_KEY, 'hex'),
algorithm: 'aes-256-gcm'
}
// Add other non-sensitive config values here
};
}
}