/** * The server's settings, from the environment (`.env`, built from `env.template.json`). Read once; * tests pass their own with `loadConfig({...})`. */ export type TrustProxy = false | number | string | string[]; export type Config = { /** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */ publicUrl: string; port: number; /** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */ secret: string; production: boolean; /** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */ trustProxySetting: TrustProxy; hubUrl: string; hubLicenceKey: string | null; hubPublicKey: string | null; /** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */ hubAdminName: string | null; hubAdminEmail: string | null; timezone: string; jobsEnabled: boolean; /** Where uploads go; default backend/uploads. */ uploadDir: string | null; /** Local testing only: linked products (Accounts) on http or private addresses. */ allowPrivateLinks: boolean; /** How long an admin stays signed in (days). */ sessionDays: number; }; const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true'); /** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */ export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy { const raw = (v ?? '').trim(); if (raw === '') return production ? 1 : false; const lower = raw.toLowerCase(); if (lower === 'true') return 1; if (lower === 'false') return false; if (/^\d+$/.test(raw)) return Number(raw) || false; return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw; } export function loadConfig(env: Record = process.env): Config { const production = env.NODE_ENV === 'production'; const secret = env.WEBSITE_SECRET || ''; if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.'); return { publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''), port: Number(env.PORT || 5300), secret: secret || 'development-only-secret-change-me-0123456789', production, trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production), hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''), hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null, hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null, hubAdminName: env.HUB_ADMIN_NAME?.trim() || null, hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null, timezone: env.APP_TIMEZONE || 'Africa/Johannesburg', jobsEnabled: bool(env.JOBS_ENABLED, true), uploadDir: env.UPLOAD_DIR?.trim() || null, allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false), sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)), }; }