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
This commit is contained in:
Leon Tonhäuser committed 2026-08-25 01:16:13 +02:00
1 parent dd60fd6ee6
commit c6b69eb88d
3 files changed
+102 -7

No files matched your search

+70
View File
@@ -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/);
});
});
+23 -5
View File
@@ -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<T extends z.ZodType>(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<typeof serverEnvSchema>;
+9 -2
View File
@@ -1,7 +1,14 @@
export async function register(): Promise<void> {
// 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);
}
}