import { EnabledLocalesConfigError, parseEnabledLocales } from "@hivegrid/i18n"; import { getEnvVariableDefinition, validateEnv } from "./index.js"; import { getDomainRoutingConfig } from "./routing.js"; import type { ApiConfig, ApiConfigDiagnostic, ApiConfigErrorDetails, ApiConfigOptions, ApiConfigResult, EnvRecord, RequiredApiConfigOptions } from "./types.js"; const DEFAULT_APP_NAME = "HiveGrid"; const DEFAULT_NODE_ENV = "development"; const DEFAULT_LISTEN_PORT = 3001; const DEFAULT_LAGO_TIMEOUT_MS = 10_000; const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000; const MIN_PORT = 1; const MAX_PORT = 65535; const MIN_SECRET_LENGTH = 32; const MAX_METRICS_TOKEN_BYTES = 512; const STRENGTH_CHECKED_SECRETS = [ "SESSION_SECRET", "CRYPTO_SECRET", "ADMIN_CONNECTION_MASTER_KEY", "JWT_SECRET", "API_ACCESS_TOKEN", "ANALYTICS_TOKEN", "AUDIT_CHAIN_SECRET", "METRICS_TOKEN", "MAILJET_WEBHOOK_SECRET", "ADMIN_EMAIL_EVENT_WEBHOOK_SECRET", "ADMIN_EMAIL_BCC_CAPABILITY_SECRET", "API_KEY_HASH_SECRET", ] as const; export class ApiConfigError extends Error { readonly diagnostics: ApiConfigDiagnostic[]; constructor(diagnostics: readonly ApiConfigDiagnostic[]) { super(formatApiConfigErrorMessage(diagnostics)); this.name = "ApiConfigError"; this.diagnostics = diagnostics.map(redactDiagnostic); } get details(): ApiConfigErrorDetails { return { diagnostics: this.diagnostics, }; } } export function loadRequiredApiConfig(env: EnvRecord = process.env, options: RequiredApiConfigOptions = {}): ApiConfig { const result = loadApiConfig(env, options); if (result.ok) { return result.config; } throw new ApiConfigError(result.diagnostics); } export function loadApiConfig(env: EnvRecord = process.env, options: ApiConfigOptions = {}): ApiConfigResult { const nodeEnv = options.nodeEnv ?? env.NODE_ENV ?? DEFAULT_NODE_ENV; const routing = getDomainRoutingConfig({ ...env, NODE_ENV: nodeEnv }); const portResult = normalizeListenPort(env.API_PORT, env.PORT); const diagnostics: ApiConfigDiagnostic[] = [ ...toDiagnostics( validateEnv(env, { target: "api", nodeEnv, includeOptionalProviders: options.includeOptionalProviders, extraRequired: options.extraRequired, }).missing ), ]; if (portResult.diagnostic) { diagnostics.push(portResult.diagnostic); } diagnostics.push(...validateApiSecretStrength(env, nodeEnv)); try { parseEnabledLocales(env.I18N_ENABLED_LOCALES, { allowReviewLocales: nodeEnv !== "production" || env.SENTRY_ENVIRONMENT?.trim().toLowerCase() === "staging", }); } catch (error) { if (!(error instanceof EnabledLocalesConfigError)) throw error; diagnostics.push({ code: "invalid-enum", name: "I18N_ENABLED_LOCALES", classification: getEnvVariableDefinition("I18N_ENABLED_LOCALES")?.classification, message: error.message, }); } const config: ApiConfig = { appName: present(env.APP_NAME) ?? DEFAULT_APP_NAME, nodeEnv, revision: present(env.APP_REVISION) ?? "unknown", listen: { port: portResult.port, }, routing, origins: { web: present(env.WEB_ORIGIN), admin: present(env.ADMIN_ORIGIN), }, apiAccessToken: present(env.API_ACCESS_TOKEN), jwtSecret: present(env.JWT_SECRET), analytics: { token: present(env.ANALYTICS_TOKEN), }, mailjet: { webhookSecret: present(env.MAILJET_WEBHOOK_SECRET), }, adminEmail: { eventWebhookSecret: present(env.ADMIN_EMAIL_EVENT_WEBHOOK_SECRET), bccCapabilitySecret: present(env.ADMIN_EMAIL_BCC_CAPABILITY_SECRET), bccInboundDomain: present(env.ADMIN_EMAIL_BCC_INBOUND_DOMAIN) ?? `bcc.${routing.appBaseDomain.split(":")[0]}`, }, lago: { apiUrl: present(env.LAGO_API_URL), apiKey: present(env.LAGO_API_KEY), webhookSecret: present(env.LAGO_WEBHOOK_SECRET), timeoutMs: normalizePositiveInteger(env.LAGO_TIMEOUT_MS, DEFAULT_LAGO_TIMEOUT_MS), }, mollie: { apiKey: present(env.MOLLIE_API_KEY), profileId: present(env.MOLLIE_PROFILE_ID), timeoutMs: normalizePositiveInteger(env.MOLLIE_TIMEOUT_MS, DEFAULT_MOLLIE_TIMEOUT_MS), }, storage: { endpoint: present(env.STORAGE_ENDPOINT), region: present(env.STORAGE_REGION), bucket: present(env.STORAGE_BUCKET), accessKeyId: present(env.STORAGE_ACCESS_KEY_ID), secretAccessKey: present(env.STORAGE_SECRET_ACCESS_KEY), sessionToken: present(env.STORAGE_SESSION_TOKEN), publicBaseUrl: present(env.STORAGE_PUBLIC_BASE_URL), forcePathStyle: present(env.STORAGE_FORCE_PATH_STYLE), }, apiKeys: { allowLegacyPlaintextFallback: parseBooleanFlag(env.API_KEY_LEGACY_PLAINTEXT_FALLBACK, false), }, }; return { ok: diagnostics.length === 0, config, diagnostics, }; } function parseBooleanFlag(value: string | undefined, defaultValue: boolean): boolean { const normalized = present(value)?.toLowerCase(); if (normalized === undefined) { return defaultValue; } if (["1", "true", "yes", "on"].includes(normalized)) { return true; } if (["0", "false", "no", "off"].includes(normalized)) { return false; } return defaultValue; } function normalizePositiveInteger(value: string | undefined, defaultValue: number): number { const trimmed = present(value); if (trimmed === undefined) { return defaultValue; } const parsed = Number(trimmed); return Number.isInteger(parsed) && parsed > 0 ? parsed : defaultValue; } function normalizeListenPort(apiPort: string | undefined, port: string | undefined): { port: number; diagnostic?: ApiConfigDiagnostic } { const selected = present(apiPort) !== undefined ? { name: "API_PORT", value: apiPort } : { name: "PORT", value: port }; const trimmed = selected.value?.trim(); if (!trimmed) { return { port: DEFAULT_LISTEN_PORT }; } const parsed = Number(trimmed); if (!Number.isInteger(parsed) || parsed < MIN_PORT || parsed > MAX_PORT) { return { port: DEFAULT_LISTEN_PORT, diagnostic: { code: "invalid-port", name: selected.name, classification: getEnvVariableDefinition(selected.name)?.classification, message: `${selected.name} must be an integer between 1 and 65535. Falling back to 3001.`, }, }; } return { port: parsed }; } function validateApiSecretStrength(env: EnvRecord, nodeEnv: string): ApiConfigDiagnostic[] { if (nodeEnv !== "production") { return []; } const diagnostics: ApiConfigDiagnostic[] = []; const firstPurposeByValue = new Map(); for (const name of STRENGTH_CHECKED_SECRETS) { const value = present(env[name]); if (!value) { continue; } const byteLength = Buffer.byteLength(value, "utf8"); if (byteLength < MIN_SECRET_LENGTH || (name === "METRICS_TOKEN" && byteLength > MAX_METRICS_TOKEN_BYTES)) { diagnostics.push({ code: "weak-secret", name, classification: getEnvVariableDefinition(name)?.classification, message: name === "METRICS_TOKEN" ? `METRICS_TOKEN must contain ${MIN_SECRET_LENGTH}..${MAX_METRICS_TOKEN_BYTES} bytes in production.` : `${name} must be at least ${MIN_SECRET_LENGTH} bytes in production.`, }); } const existingPurpose = firstPurposeByValue.get(value); if (existingPurpose) { diagnostics.push({ code: "weak-secret", name, classification: getEnvVariableDefinition(name)?.classification, message: `${name} must use an independent value and must not be identical to ${existingPurpose}.`, }); } else { firstPurposeByValue.set(value, name); } } return diagnostics; } function toDiagnostics(issues: ReturnType["missing"]): ApiConfigDiagnostic[] { return issues.map((issue) => ({ code: "missing-required", name: issue.name, classification: issue.classification, message: issue.message, })); } function formatApiConfigErrorMessage(diagnostics: readonly ApiConfigDiagnostic[]): string { const summary = diagnostics.map((diagnostic) => `${diagnostic.name}:${diagnostic.code}`).join(", "); return `Invalid API configuration (${summary}).`; } function redactDiagnostic(diagnostic: ApiConfigDiagnostic): ApiConfigDiagnostic { return { code: diagnostic.code, name: diagnostic.name, classification: diagnostic.classification, message: diagnostic.message, }; } function present(value: string | undefined): string | undefined { const trimmed = value?.trim(); return trimmed ? trimmed : undefined; }