From c6b69eb88dd0f3a28c47f437cd557bc326e4745c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Tue, 25 Aug 2026 01:16:13 +0200 Subject: [PATCH] fix: survive empty-string env vars from compose Docker Compose passes undeclared variables as empty strings (CRON_SECRET="" etc.), which crashed env validation while loading the instrumentation hook. A throwing register() made Next.js answer every route with 500 while the process stayed alive. - parse optional CRON_SECRET / AUTO_RULE_SYNC_INTERVAL_SECONDS via plain preprocess helpers that map blank strings to unset (zod v4 does not accept preprocess-produced undefined through .optional()) - guard instrumentation register() so scheduler failures can never break request handling --- src/config/env.test.ts | 70 ++++++++++++++++++++++++++++++++++++++++++ src/config/env.ts | 28 ++++++++++++++--- src/instrumentation.ts | 11 +++++-- 3 files changed, 102 insertions(+), 7 deletions(-) diff --git a/src/config/env.test.ts b/src/config/env.test.ts index 04a5736..e30f5b0 100644 --- a/src/config/env.test.ts +++ b/src/config/env.test.ts @@ -29,5 +29,75 @@ describe("parseServerEnv", () => { "https://leon-tonhaeuser.de/datenschutz", ); expect(parsed.LEGAL_TERMS_URL).toBe("https://leon-tonhaeuser.de/agb"); + expect(parsed.CRON_SECRET).toBeUndefined(); + expect(parsed.AUTO_RULE_SYNC_INTERVAL_SECONDS).toBeUndefined(); + }); + + test.each([ + { label: "empty string", CRON_SECRET: "", AUTO_RULE_SYNC_INTERVAL_SECONDS: "" }, + { label: "whitespace only", CRON_SECRET: " ", AUTO_RULE_SYNC_INTERVAL_SECONDS: " " }, + ])( + "treats $label optional vars as unset (docker compose passes empty strings)", + ({ CRON_SECRET, AUTO_RULE_SYNC_INTERVAL_SECONDS }) => { + const parsed = parseServerEnv({ + DATABASE_URL: "postgres://portal:secret@portal-db:5432/portal", + BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters", + BETTER_AUTH_URL: "https://redaktionen.leon-tonhaeuser.de", + IMMICH_BASE_URL: "http://immich-server:2283", + IMMICH_API_KEY: "test-immich-key", + SMTP_HOST: "smtp.example.com", + SMTP_PORT: "587", + SMTP_USER: "portal@example.com", + SMTP_PASSWORD: "test-smtp-password", + SMTP_FROM: "portal@example.com", + CRON_SECRET, + AUTO_RULE_SYNC_INTERVAL_SECONDS, + }); + + expect(parsed.CRON_SECRET).toBeUndefined(); + expect(parsed.AUTO_RULE_SYNC_INTERVAL_SECONDS).toBeUndefined(); + }, + ); + + test("parses configured optional values", () => { + const parsed = parseServerEnv({ + DATABASE_URL: "postgres://portal:secret@portal-db:5432/portal", + BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters", + BETTER_AUTH_URL: "https://redaktionen.leon-tonhaeuser.de", + IMMICH_BASE_URL: "http://immich-server:2283", + IMMICH_API_KEY: "test-immich-key", + SMTP_HOST: "smtp.example.com", + SMTP_PORT: "587", + SMTP_USER: "portal@example.com", + SMTP_PASSWORD: "test-smtp-password", + SMTP_FROM: "portal@example.com", + CRON_SECRET: "cron-secret-at-least-16-chars", + AUTO_RULE_SYNC_INTERVAL_SECONDS: "60", + }); + + expect(parsed.CRON_SECRET).toBe("cron-secret-at-least-16-chars"); + expect(parsed.AUTO_RULE_SYNC_INTERVAL_SECONDS).toBe(60); + }); + + test("rejects invalid optional values with a clear message", () => { + const base = { + DATABASE_URL: "postgres://portal:secret@portal-db:5432/portal", + BETTER_AUTH_SECRET: "test-secret-at-least-thirty-two-characters", + BETTER_AUTH_URL: "https://redaktionen.leon-tonhaeuser.de", + IMMICH_BASE_URL: "http://immich-server:2283", + IMMICH_API_KEY: "test-immich-key", + SMTP_HOST: "smtp.example.com", + SMTP_PORT: "587", + SMTP_USER: "portal@example.com", + SMTP_PASSWORD: "test-smtp-password", + SMTP_FROM: "portal@example.com", + }; + + expect(() => + parseServerEnv({ ...base, CRON_SECRET: "short" }), + ).toThrow(/CRON_SECRET must be at least 16 characters/); + expect(() => + parseServerEnv({ ...base, AUTO_RULE_SYNC_INTERVAL_SECONDS: "10" }), + ).toThrow(/AUTO_RULE_SYNC_INTERVAL_SECONDS must be >= 30/); }); }); diff --git a/src/config/env.ts b/src/config/env.ts index 3cc25e8..c775f99 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -21,15 +21,33 @@ const serverEnvSchema = z.object({ .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: emptyToUndefined(z.string().min(16)).optional(), + CRON_SECRET: optionalSecret(), /** How often the album auto-rule sync runs, in seconds (min 30). */ - AUTO_RULE_SYNC_INTERVAL_SECONDS: emptyToUndefined(z.coerce.number().int().min(30)).optional(), + AUTO_RULE_SYNC_INTERVAL_SECONDS: optionalIntervalSeconds(), }); // Docker Compose passes undeclared vars as empty strings; treat those as -// unset so optional settings stay optional. -function emptyToUndefined(schema: T) { - return z.preprocess((value) => (value === "" ? undefined : value), schema); +// 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; diff --git a/src/instrumentation.ts b/src/instrumentation.ts index 726e813..1937cd8 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -1,7 +1,14 @@ export async function register(): Promise { + // The album auto-rule sync is best-effort: a failure here must never take + // down request handling (a throwing register() makes Next.js answer every + // route with 500). if (process.env.NEXT_RUNTIME !== "nodejs") { return; } - const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler"); - startAutoRuleScheduler(); + try { + const { startAutoRuleScheduler } = await import("@/modules/albums/auto-rule-scheduler"); + startAutoRuleScheduler(); + } catch (error) { + console.error("[auto-rule-sync] scheduler disabled after startup error:", error); + } }