Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 880x 882x 2x 2x 88x 88x 2x 2x 90x 2x 2x 4x 2x 2x 88x 264x 266x 88x 2x 2x 2x 20x 20x 20x 20x 20x 20x 20x 88x 2x 2x 2x 2x 2x 2x 2x 88x 2x 6x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 88x 2x 88x 9x 9x 9x 2x 2x 9x 2x 2x 2x 2x 9x 9x 79x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x 2x 2x 2x 2x 88x | // src/config/env.ts /** * @file Centralized, schema-validated configuration service. * Implements ADR-007: Configuration and Secrets Management. * * This module parses and validates all environment variables at application startup. * If any required configuration is missing or invalid, the application will fail fast * with a clear error message. * * Usage: * import { config } from './config/env'; * console.log(config.database.host); */ import { z } from 'zod'; // --- Schema Definitions --- /** * Helper to parse string to integer with default. * Handles empty strings by treating them as undefined. */ const intWithDefault = (defaultValue: number) => z .string() .optional() .transform((val) => (val && val.trim() !== '' ? parseInt(val, 10) : defaultValue)) .pipe(z.number().int()); /** * Helper to parse string to float with default. */ const floatWithDefault = (defaultValue: number) => z .string() .optional() .transform((val) => (val && val.trim() !== '' ? parseFloat(val) : defaultValue)) .pipe(z.number()); /** * Helper to parse string 'true'/'false' to boolean. */ const booleanString = (defaultValue: boolean) => z .string() .optional() .transform((val) => (val === undefined ? defaultValue : val === 'true')); /** * Database configuration schema. */ const databaseSchema = z.object({ host: z.string().min(1, 'DB_HOST is required'), port: intWithDefault(5432), user: z.string().min(1, 'DB_USER is required'), password: z.string().min(1, 'DB_PASSWORD is required'), name: z.string().min(1, 'DB_NAME is required'), }); /** * Redis configuration schema. */ const redisSchema = z.object({ url: z.string().url('REDIS_URL must be a valid URL'), password: z.string().optional(), }); /** * Authentication configuration schema. */ const authSchema = z.object({ jwtSecret: z.string().min(32, 'JWT_SECRET must be at least 32 characters for security'), jwtSecretPrevious: z.string().optional(), // For secret rotation (ADR-029) }); /** * SMTP/Email configuration schema. * All fields are optional - email service degrades gracefully if not configured. */ const smtpSchema = z.object({ host: z.string().optional(), port: intWithDefault(587), user: z.string().optional(), pass: z.string().optional(), secure: booleanString(false), fromEmail: z.string().email().optional(), }); /** * AI/Gemini configuration schema. */ const aiSchema = z.object({ geminiApiKey: z.string().optional(), geminiRpm: intWithDefault(5), priceQualityThreshold: floatWithDefault(0.5), }); /** * UPC API configuration schema. * External APIs for product lookup by barcode. */ const upcSchema = z.object({ upcItemDbApiKey: z.string().optional(), // UPC Item DB API key (upcitemdb.com) barcodeLookupApiKey: z.string().optional(), // Barcode Lookup API key (barcodelookup.com) }); /** * Google services configuration schema. */ const googleSchema = z.object({ mapsApiKey: z.string().optional(), clientId: z.string().optional(), clientSecret: z.string().optional(), }); /** * Worker concurrency configuration schema. */ const workerSchema = z.object({ concurrency: intWithDefault(1), lockDuration: intWithDefault(30000), emailConcurrency: intWithDefault(10), analyticsConcurrency: intWithDefault(1), cleanupConcurrency: intWithDefault(10), weeklyAnalyticsConcurrency: intWithDefault(1), }); /** * Server configuration schema. */ const serverSchema = z.object({ nodeEnv: z.enum(['development', 'production', 'test', 'staging']).default('development'), port: intWithDefault(3001), frontendUrl: z.string().url().optional(), baseUrl: z.string().optional(), storagePath: z.string().default('/var/www/flyer-crawler.projectium.com/flyer-images'), }); /** * Error tracking configuration schema (ADR-015). * Uses Bugsink (Sentry-compatible self-hosted error tracking). */ const sentrySchema = z.object({ dsn: z.string().optional(), // Sentry DSN for backend enabled: booleanString(true), environment: z.string().optional(), debug: booleanString(false), }); /** * Complete environment configuration schema. */ const envSchema = z.object({ database: databaseSchema, redis: redisSchema, auth: authSchema, smtp: smtpSchema, ai: aiSchema, upc: upcSchema, google: googleSchema, worker: workerSchema, server: serverSchema, sentry: sentrySchema, }); export type EnvConfig = z.infer<typeof envSchema>; // --- Configuration Loading --- /** * Maps environment variables to the configuration structure. * This is the single source of truth for which env vars map to which config keys. */ function loadEnvVars(): unknown { return { database: { host: process.env.DB_HOST, port: process.env.DB_PORT, user: process.env.DB_USER, password: process.env.DB_PASSWORD, name: process.env.DB_NAME, }, redis: { url: process.env.REDIS_URL, password: process.env.REDIS_PASSWORD, }, auth: { jwtSecret: process.env.JWT_SECRET, jwtSecretPrevious: process.env.JWT_SECRET_PREVIOUS, }, smtp: { host: process.env.SMTP_HOST, port: process.env.SMTP_PORT, user: process.env.SMTP_USER, pass: process.env.SMTP_PASS, secure: process.env.SMTP_SECURE, fromEmail: process.env.SMTP_FROM_EMAIL, }, ai: { geminiApiKey: process.env.GEMINI_API_KEY, geminiRpm: process.env.GEMINI_RPM, priceQualityThreshold: process.env.AI_PRICE_QUALITY_THRESHOLD, }, upc: { upcItemDbApiKey: process.env.UPC_ITEM_DB_API_KEY, barcodeLookupApiKey: process.env.BARCODE_LOOKUP_API_KEY, }, google: { mapsApiKey: process.env.GOOGLE_MAPS_API_KEY, clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }, worker: { concurrency: process.env.WORKER_CONCURRENCY, lockDuration: process.env.WORKER_LOCK_DURATION, emailConcurrency: process.env.EMAIL_WORKER_CONCURRENCY, analyticsConcurrency: process.env.ANALYTICS_WORKER_CONCURRENCY, cleanupConcurrency: process.env.CLEANUP_WORKER_CONCURRENCY, weeklyAnalyticsConcurrency: process.env.WEEKLY_ANALYTICS_WORKER_CONCURRENCY, }, server: { nodeEnv: process.env.NODE_ENV, port: process.env.PORT, frontendUrl: process.env.FRONTEND_URL, baseUrl: process.env.BASE_URL, storagePath: process.env.STORAGE_PATH, }, sentry: { dsn: process.env.SENTRY_DSN, enabled: process.env.SENTRY_ENABLED, environment: process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV, debug: process.env.SENTRY_DEBUG, }, }; } /** * Validates and parses environment configuration. * Throws a descriptive error if validation fails. */ function parseConfig(): EnvConfig { const rawConfig = loadEnvVars(); const result = envSchema.safeParse(rawConfig); if (!result.success) { const errors = result.error.issues.map((issue) => { const path = issue.path.join('.'); return ` - ${path}: ${issue.message}`; }); const errorMessage = [ '', '╔════════════════════════════════════════════════════════════════╗', '║ CONFIGURATION ERROR - APPLICATION STARTUP ║', '╚════════════════════════════════════════════════════════════════╝', '', 'The following environment variables are missing or invalid:', '', ...errors, '', 'Please check your .env file or environment configuration.', 'See ADR-007 for the complete list of required environment variables.', '', ].join('\n'); // In test/staging environment, throw instead of exiting to allow test frameworks to catch // and to provide better visibility into config errors during staging deployments Eif (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'staging') { throw new Error(errorMessage); } console.error(errorMessage); process.exit(1); } return result.data; } // --- Exported Configuration --- /** * The validated application configuration. * This is a singleton that is parsed once at module load time. * * @example * ```typescript * import { config } from './config/env'; * * // Access database config * const pool = new Pool({ * host: config.database.host, * port: config.database.port, * user: config.database.user, * password: config.database.password, * database: config.database.name, * }); * * // Check environment * if (config.server.isProduction) { * // production-only logic * } * ``` */ export const config: EnvConfig = parseConfig(); // --- Convenience Helpers --- /** * Returns true if running in production environment. */ export const isProduction = config.server.nodeEnv === 'production'; /** * Returns true if running in test environment. */ export const isTest = config.server.nodeEnv === 'test'; /** * Returns true if running in development environment. */ export const isDevelopment = config.server.nodeEnv === 'development'; /** * Returns true if running in staging environment. */ export const isStaging = config.server.nodeEnv === 'staging'; /** * Returns true if running in a test-like environment (test or staging). * Use this for behaviors that should be shared between unit/integration tests * and the staging deployment server, such as: * - Using mock AI services (no GEMINI_API_KEY required) * - Verbose error logging * - Fallback URL handling * * Do NOT use this for security bypasses (auth, rate limiting) - those should * only be active in NODE_ENV=test, not staging. */ export const isTestLikeEnvironment = isTest || isStaging; /** * Returns true if SMTP is configured (all required fields present). */ export const isSmtpConfigured = !!config.smtp.host && !!config.smtp.user && !!config.smtp.pass && !!config.smtp.fromEmail; /** * Returns true if AI services are configured. */ export const isAiConfigured = !!config.ai.geminiApiKey; /** * Returns true if Google Maps is configured. */ export const isGoogleMapsConfigured = !!config.google.mapsApiKey; /** * Returns true if Sentry/Bugsink error tracking is configured and enabled. */ export const isSentryConfigured = !!config.sentry.dsn && config.sentry.enabled; /** * Returns true if UPC Item DB API is configured. */ export const isUpcItemDbConfigured = !!config.upc.upcItemDbApiKey; /** * Returns true if Barcode Lookup API is configured. */ export const isBarcodeLookupConfigured = !!config.upc.barcodeLookupApiKey; |