import type { AppConfig, Environment } from './app-config.interface.js'; export const APP_CONFIG = Symbol('APP_CONFIG'); const ENVIRONMENTS: Environment[] = ['development', 'test', 'staging', 'production']; export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig { const problems: string[] = []; const required = (name: string) => { const value = env[name]?.trim(); if (!value) problems.push(`${name} is required`); return value ?? ''; }; const integer = (name: string, fallback: number) => { const raw = env[name]?.trim(); if (!raw) return fallback; const value = Number(raw); if (!Number.isInteger(value) || value < 0) problems.push(`${name} must be a whole number`); return value; }; const environment = (env.ENVIRONMENT ?? 'development') as Environment; if (!ENVIRONMENTS.includes(environment)) problems.push(`ENVIRONMENT must be one of ${ENVIRONMENTS.join(', ')}`); let allowedOriginRegex: RegExp | null = null; const regex = env.PREVISION_ALLOWED_ORIGIN_REGEX?.trim(); if (regex) { try { allowedOriginRegex = new RegExp(`^(?:${regex.replace(/^\^|\$$/g, '')})$`); } catch { problems.push('PREVISION_ALLOWED_ORIGIN_REGEX is not a valid regular expression'); } } const config: AppConfig = { environment, port: integer('PREVISION_API_PORT', 8001), databaseUrl: required('PREVISION_DATABASE_URL'), allowedOrigins: (env.PREVISION_ALLOWED_ORIGINS ?? 'http://localhost:5173') .split(',') .map((origin) => origin.trim().replace(/\/$/, '')) .filter(Boolean), allowedOriginRegex, clerk: { secretKeys: required('CLERK_SECRET_KEY') .split(',') .map((key) => key.trim()) .filter(Boolean), jwtKey: env.CLERK_JWT_KEY?.trim() || undefined, }, processingToken: { secret: required('PROCESSING_TOKEN_SECRET'), ttlSeconds: integer('PROCESSING_TOKEN_TTL_SECONDS', 600), audience: env.PROCESSING_TOKEN_AUDIENCE?.trim() || 'prevision-processing', issuer: 'prevision-api', }, internalTokenAudience: 'prevision-internal', freeGenerations: integer('FREE_GENERATIONS', 10), appUrl: (env.PREVISION_APP_URL?.trim() || 'http://localhost:5173').replace(/\/$/, ''), stripe: { secretKey: required('STRIPE_SECRET_KEY'), webhookSecret: required('STRIPE_WEBHOOK_SECRET'), plans: { starter: { priceId: required('STRIPE_PRICE_STARTER'), monthlyGenerations: integer('STARTER_MONTHLY_GENERATIONS', 150) }, growth: { priceId: required('STRIPE_PRICE_GROWTH'), monthlyGenerations: integer('GROWTH_MONTHLY_GENERATIONS', 600) }, }, logoUrl: env.STRIPE_LOGO_URL?.trim() || undefined, portalConfigurationId: env.STRIPE_PORTAL_CONFIGURATION_ID?.trim() || undefined, }, }; if (environment === 'staging' || environment === 'production') { if (config.processingToken.secret.length < 32) problems.push('PROCESSING_TOKEN_SECRET must be at least 32 characters'); if (config.allowedOrigins.some((origin) => origin.includes('*'))) problems.push('PREVISION_ALLOWED_ORIGINS must list exact origins'); if (!config.clerk.secretKeys.every((key) => key.startsWith('sk_'))) problems.push('CLERK_SECRET_KEY must list Clerk secret keys'); if (!/^(sk|rk)_/.test(config.stripe.secretKey)) problems.push('STRIPE_SECRET_KEY must be a Stripe secret key'); if (!config.stripe.webhookSecret.startsWith('whsec_')) problems.push('STRIPE_WEBHOOK_SECRET must be a webhook signing secret'); if (!config.appUrl.startsWith('https://')) problems.push('PREVISION_APP_URL must be an https URL'); } if (problems.length) throw new Error(`Invalid configuration: ${problems.join('; ')}`); return config; } export function isOriginAllowed(config: AppConfig, origin: string | null | undefined): boolean { if (!origin) return false; const normalized = origin.replace(/\/$/, ''); return config.allowedOrigins.includes(normalized) || Boolean(config.allowedOriginRegex?.test(normalized)); }