Yaltopia-Homes-TGClient/src/utils/envValidator.js

89 lines
2.8 KiB
JavaScript

class EnvironmentValidator {
static validateEnvironment() {
const requiredEnvVars = [
'TELEGRAM_BOT_TOKEN',
'API_BASE_URL'
];
const missingVars = [];
const invalidVars = [];
for (const envVar of requiredEnvVars) {
const value = process.env[envVar];
if (!value) {
missingVars.push(envVar);
continue;
}
// Validate specific environment variables
switch (envVar) {
case 'TELEGRAM_BOT_TOKEN':
if (!this.validateTelegramToken(value)) {
invalidVars.push(`${envVar}: Invalid token format`);
}
break;
case 'API_BASE_URL':
if (!this.validateApiUrl(value)) {
invalidVars.push(`${envVar}: Invalid URL format`);
}
break;
}
}
if (missingVars.length > 0) {
console.error('❌ Missing required environment variables:');
missingVars.forEach(varName => {
console.error(` - ${varName}`);
});
console.error('\nPlease check your .env file and ensure all required variables are set.');
return false;
}
if (invalidVars.length > 0) {
console.error('❌ Invalid environment variables:');
invalidVars.forEach(error => {
console.error(` - ${error}`);
});
return false;
}
console.log('✅ Environment validation passed');
return true;
}
static validateTelegramToken(token) {
// Telegram bot tokens have a specific format: number:string
const tokenRegex = /^\d+:[A-Za-z0-9_-]{35}$/;
return tokenRegex.test(token);
}
static validateApiUrl(url) {
try {
const parsedUrl = new URL(url);
// Ensure HTTPS in production (allow HTTP for development)
if (process.env.NODE_ENV === 'production' && parsedUrl.protocol !== 'https:') {
console.warn('⚠️ WARNING: Using HTTP in production is not secure');
return false;
}
return ['http:', 'https:'].includes(parsedUrl.protocol);
} catch (error) {
return false;
}
}
static getSecureConfig() {
return {
telegramBotToken: process.env.TELEGRAM_BOT_TOKEN,
apiBaseUrl: process.env.API_BASE_URL,
websiteUrl: process.env.WEBSITE_URL || 'https://yaltipia.com/listings',
nodeEnv: process.env.NODE_ENV || 'development',
isProduction: process.env.NODE_ENV === 'production'
};
}
}
module.exports = EnvironmentValidator;