File size: 4,174 Bytes
33927c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46ab86e
33927c8
 
46ab86e
 
33927c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f237798
 
 
33927c8
 
 
 
 
 
 
d08bef8
33927c8
 
 
 
 
 
f237798
33927c8
 
 
 
d08bef8
33927c8
 
 
 
d08bef8
33927c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/**
 * SECURE ENVIRONMENT VALIDATOR
 * 
 * This validates environment variables without exposing their values
 * and provides helpful error messages for missing configuration.
 */

import { logger } from './secureLogger';

interface EnvironmentConfig {
  supabaseUrl: string;
  supabaseAnonKey: string;
  apiBaseUrl: string;
  isDevelopment: boolean;
  isProduction: boolean;
}

class SecureEnvironment {
  private config: EnvironmentConfig | null = null;
  private validationError: string | null = null;

  /**
   * Validate and load environment configuration
   * Returns sanitized config without exposing actual values
   */
  public validateAndLoad(): EnvironmentConfig {
    if (this.config && !this.validationError) {
      return this.config;
    }

    try {
      const env = (typeof import.meta !== 'undefined' && import.meta.env) ? import.meta.env : (process.env as any);
      
      // Check for required environment variables
      const supabaseUrl = env.VITE_SUPABASE_URL || env.SUPABASE_URL;
      const supabaseAnonKey = env.VITE_SUPABASE_ANON_KEY || env.SUPABASE_ANON_KEY;
      
      if (!supabaseUrl) {
        throw new Error('VITE_SUPABASE_URL is required');
      }
      
      if (!supabaseAnonKey) {
        throw new Error('VITE_SUPABASE_ANON_KEY is required');
      }

      // Validate URL format
      if (!supabaseUrl.startsWith('https://') || !supabaseUrl.includes('.supabase.co')) {
        throw new Error('VITE_SUPABASE_URL must be a valid Supabase URL');
      }

      // Check for dangerous environment variables that shouldn't be in client
      const dangerousVars = [
        'VITE_GEMMA_API_KEY',
        'VITE_OPENROUTER_API_KEY',
        // Legacy names kept for leak detection during migration cleanups.
        'VITE_GEMINI_API_KEY_1', 'VITE_GEMINI_API_KEY_2', 'VITE_GEMINI_API_KEY_3',
        'VITE_GEMINI_API_KEY_4', 'VITE_GEMINI_API_KEY_5'
      ];

      const foundDangerousVars = dangerousVars.filter(varName => env[varName]);
      
      if (foundDangerousVars.length > 0 && env.NODE_ENV === 'production') {
        logger.error('[Security] WARNING: Sensitive API keys found in production environment');
        logger.error('These variables should be removed from client-side code:', foundDangerousVars);
      }

      this.config = {
        supabaseUrl,
        supabaseAnonKey,
        apiBaseUrl: env.VITE_API_BASE_URL || 'http://localhost:3001',
        isDevelopment: env.NODE_ENV === 'development',
        isProduction: env.NODE_ENV === 'production'
      };

      logger.log('[Security] Environment configuration validated successfully');
      return this.config;

    } catch (error) {
      this.validationError = error instanceof Error ? error.message : 'Unknown validation error';
      logger.error('[Security] Environment validation failed:', this.validationError);
      throw error;
    }
  }

  /**
   * Get sanitized environment info for debugging (no sensitive values)
   */
  public getEnvironmentInfo(): Record<string, any> {
    const config = this.validateAndLoad();
    
    return {
      supabaseConfigured: !!config.supabaseUrl,
      supabaseUrl: config.supabaseUrl ? config.supabaseUrl.substring(0, 20) + '...' : 'Not configured',
      apiBaseUrl: config.apiBaseUrl,
      environment: config.isProduction ? 'production' : 'development',
      securityLevel: config.isProduction ? 'high' : 'development'
    };
  }

  /**
   * Check if all required configuration is present
   */
  public isConfigurationValid(): boolean {
    try {
      this.validateAndLoad();
      return true;
    } catch {
      return false;
    }
  }

  /**
   * Get configuration error message if validation failed
   */
  public getConfigurationError(): string | null {
    return this.validationError;
  }
}

// Export singleton instance
export const secureEnv = new SecureEnvironment();

// Export configuration getter
export function getSecureConfig(): EnvironmentConfig {
  return secureEnv.validateAndLoad();
}

// Export environment info for debugging (safe to display)
export function getEnvironmentInfo(): Record<string, any> {
  return secureEnv.getEnvironmentInfo();
}

export default secureEnv;