import "server-only"; import { z } from "zod"; const serverEnvSchema = z.object({ DATABASE_URL: z.url(), BETTER_AUTH_SECRET: z.string().min(32), BETTER_AUTH_URL: z.url(), IMMICH_BASE_URL: z.url(), IMMICH_API_KEY: z.string().min(1), SMTP_HOST: z.string().min(1), SMTP_PORT: z.coerce.number().int().min(1).max(65_535), SMTP_USER: z.string().min(1), SMTP_PASSWORD: z.string().min(1), SMTP_FROM: z.string().min(1), LEGAL_IMPRINT_URL: z .url() .default("https://leon-tonhaeuser.de/impressum"), LEGAL_PRIVACY_URL: z .url() .default("https://leon-tonhaeuser.de/datenschutz"), LEGAL_TERMS_URL: z.url().default("https://leon-tonhaeuser.de/agb"), /** Bearer token for the /api/cron/album-sync endpoint; unset disables it. */ CRON_SECRET: optionalSecret(), /** How often the album auto-rule sync runs, in seconds (min 30). */ AUTO_RULE_SYNC_INTERVAL_SECONDS: optionalIntervalSeconds(), }); // Docker Compose passes undeclared vars as empty strings; treat those as // unset so optional settings stay optional. Implemented with plain // preprocess functions because wrapping z.preprocess(...).optional() does // NOT accept the produced undefined in zod v4 (the inner schema still runs). function emptyStringToUndefined(value: unknown): unknown { return typeof value === "string" && value.trim() === "" ? undefined : value; } function optionalSecret() { return z.preprocess( emptyStringToUndefined, z.string().min(16, "CRON_SECRET must be at least 16 characters").optional(), ); } function optionalIntervalSeconds() { return z.preprocess((value) => { const normalized = emptyStringToUndefined(value); if (normalized === undefined) return undefined; if (/^\d+$/.test(String(normalized))) return Number(normalized); return normalized; }, z.number().int().min(30, "AUTO_RULE_SYNC_INTERVAL_SECONDS must be >= 30").optional()); } export type ServerEnv = z.infer; export function parseServerEnv(input: NodeJS.ProcessEnv): ServerEnv; export function parseServerEnv( input: Record, ): ServerEnv; export function parseServerEnv( input: NodeJS.ProcessEnv | Record, ): ServerEnv { return serverEnvSchema.parse(input); } export const env = parseServerEnv(process.env);