import { plainToInstance } from 'class-transformer'; import { IsIn, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl, Max, Min, validateSync } from 'class-validator'; /** `sslmode` values that encrypt the database connection (the pg driver treats them all as `verify-full`). */ const SECURE_SSL_MODES = ['require', 'verify-ca', 'verify-full']; /** Environment variables read by the app. A missing or malformed required one stops the startup. */ export class EnvironmentVariables { /** `production` enforces production-only rules (TLS to the database). */ @IsOptional() @IsIn(['development', 'production', 'test']) NODE_ENV?: string; /** In production, `sslmode` must be require, verify-ca or verify-full: customer data must not travel in clear. */ @IsString() @IsNotEmpty() DATABASE_URL!: string; /** HTTPS only: the Hiboutik credentials are sent with HTTP Basic auth. */ @IsUrl({ protocols: ['https'], require_protocol: true }) HIBOUTIK_BASE_URL!: string; @IsString() @IsNotEmpty() HIBOUTIK_USERNAME!: string; @IsString() @IsNotEmpty() HIBOUTIK_PASSWORD!: string; @IsOptional() @IsInt() @Min(1) @Max(65535) PORT?: number; /** Comma-separated list of origins allowed by CORS. Empty or unset: CORS stays disabled. */ @IsOptional() @IsString() CORS_ORIGINS?: string; /** Number of reverse proxies in front of the app (so the real client IP is used for rate limiting). Unset: no proxy. */ @IsOptional() @IsInt() @Min(1) @Max(10) TRUST_PROXY?: number; /** * Seconds a shutting down instance waits for its running synchronization (default 25). Keep it below the grace period * of the orchestrator (Docker `stop_grace_period`, Kubernetes `terminationGracePeriodSeconds`), which kills afterwards. */ @IsOptional() @IsInt() @Min(0) @Max(3600) SYNC_SHUTDOWN_TIMEOUT?: number; } /** Whether the connection string asks for an encrypted connection. An unparsable one does not. */ function hasSecureSslMode(databaseUrl: string): boolean { try { return SECURE_SSL_MODES.includes(new URL(databaseUrl).searchParams.get('sslmode') ?? ''); } catch { return false; } } /** `ConfigModule` validation hook: fails fast with the names of the faulty variables (never their values, they may be secrets). */ export function validateEnv(config: Record): Record { const validated = plainToInstance(EnvironmentVariables, config, { enableImplicitConversion: true }); const errors = validateSync(validated, { whitelist: false }); const details = errors.map((error) => `${error.property}: ${Object.values(error.constraints ?? {}).join(', ')}`); if (validated.NODE_ENV === 'production' && validated.DATABASE_URL && !hasSecureSslMode(validated.DATABASE_URL)) { details.push(`DATABASE_URL: sslmode must be one of ${SECURE_SSL_MODES.join(', ')} in production`); } if (details.length > 0) { throw new Error(`Invalid environment configuration:\n ${details.join('\n ')}`); } return config; }