diff --git a/scripts/preflight.ts b/scripts/preflight.ts new file mode 100644 index 0000000..6834c4f --- /dev/null +++ b/scripts/preflight.ts @@ -0,0 +1,182 @@ +// Preflight smoke test for the Redaktionsportal deployment. +// Validates that every required env var is set, then checks live connectivity +// to the database, the Better Auth adapter, SMTP and Immich. +// +// Run where the production env is available, e.g. on the host: +// set -a; . ./.env; set +a; pnpm tsx scripts/preflight.ts + +const REQUIRED_ENV = [ + "DATABASE_URL", + "BETTER_AUTH_SECRET", + "BETTER_AUTH_URL", + "IMMICH_BASE_URL", + "IMMICH_API_KEY", + "SMTP_HOST", + "SMTP_PORT", + "SMTP_USER", + "SMTP_PASSWORD", + "SMTP_FROM", + "LEGAL_IMPRINT_URL", + "LEGAL_PRIVACY_URL", + "LEGAL_TERMS_URL", +] as const; + +const AUTH_TABLES = ["user", "account", "session", "verification"]; + +type Outcome = { ok: boolean; detail: string }; + +function icon(ok: boolean): string { + return ok ? "OK " : "FAIL "; +} + +function zodIssues(error: unknown): string { + if (error && typeof error === "object" && "issues" in error && Array.isArray(error.issues)) { + const list = error.issues.map( + (i: { path?: unknown[]; message: string }) => + `${(i.path ?? []).join(".") || "(root)"}: ${i.message}`, + ); + return `ungültig — ${list.join("; ")}`; + } + return error instanceof Error ? error.message : String(error); +} + +async function main() { + console.log(`\nPreflight Redaktionsportal\n${"─".repeat(48)}`); + + let failed = 0; + const report = (label: string, { ok, detail }: Outcome) => { + if (!ok) failed += 1; + console.log(`${icon(ok)} ${label.padEnd(7)} ${detail}`); + }; + + // 1. ENV — presence first, then full Zod validation. Done before importing + // app modules so a missing/invalid var is reported, not crashed on. + const missing = REQUIRED_ENV.filter((key) => !process.env[key]?.trim()); + let env: Awaited["env"]; + if (missing.length > 0) { + report("ENV", { ok: false, detail: `nicht gesetzt: ${missing.join(", ")}` }); + console.log("\nÜbrige Prüfungen übersprungen (ENV ungültig).\n"); + process.exit(1); + } + try { + const envModule = await import("../src/config/env"); + envModule.parseServerEnv(process.env); + env = envModule.env; + report("ENV", { ok: true, detail: "alle Variablen gesetzt und gültig" }); + } catch (error) { + report("ENV", { ok: false, detail: zodIssues(error) }); + console.log("\nÜbrige Prüfungen übersprungen (ENV ungültig).\n"); + process.exit(1); + } + + const { pool } = await import("../src/db/client"); + const nodemailer = (await import("nodemailer")).default; + + // 2. DB — reachable? + try { + await pool.query("SELECT 1"); + report("DB", { ok: true, detail: "Verbindung OK (SELECT 1)" }); + } catch (error) { + report("DB", { + ok: false, + detail: error instanceof Error ? error.message : String(error), + }); + } + + // 3. MIGRATIONS — Better Auth tables present? + try { + const result = await pool.query<{ table_name: string }>( + `SELECT table_name FROM information_schema.tables + WHERE table_schema = 'public' AND table_name = ANY($1)`, + [AUTH_TABLES], + ); + const present = new Set(result.rows.map((r) => r.table_name)); + const absent = AUTH_TABLES.filter((t) => !present.has(t)); + report("MIGRATE", { + ok: absent.length === 0, + detail: + absent.length === 0 + ? "Better-Auth-Tabellen vorhanden (user, account, session, verification)" + : `Tabellen fehlen — Migrations nicht ausgeführt? fehlt: ${absent.join(", ")}`, + }); + } catch (error) { + report("MIGRATE", { + ok: false, + detail: error instanceof Error ? error.message : String(error), + }); + } + + // 4. AUTH — Better Auth instance builds with this config AND the user table + // is readable through the configured DB. Importing auth forces the config + // to validate; the count query forces a real DB read (no false OK when + // the DB is down, unlike auth.api.getSession with no cookie). + try { + await import("../src/modules/auth/auth"); + const result = await pool.query<{ n: number }>(`SELECT count(*)::int AS n FROM "user"`); + report("AUTH", { + ok: true, + detail: `OK — Better Auth initialisiert, ${result.rows[0]?.n ?? 0} User`, + }); + } catch (error) { + report("AUTH", { + ok: false, + detail: error instanceof Error ? error.message : String(error), + }); + } + + // 5. SMTP — connection + auth against the configured transport. + try { + const transport = nodemailer.createTransport({ + host: env.SMTP_HOST, + port: env.SMTP_PORT, + secure: env.SMTP_PORT === 465, + auth: { user: env.SMTP_USER, pass: env.SMTP_PASSWORD }, + }); + await transport.verify(); + report("SMTP", { + ok: true, + detail: `Verbindung OK — ${env.SMTP_HOST}:${env.SMTP_PORT} als ${env.SMTP_USER} (from=${env.SMTP_FROM})`, + }); + } catch (error) { + report("SMTP", { + ok: false, + detail: error instanceof Error ? error.message : String(error), + }); + } + + // 6. IMMICH — API reachable with the configured key. + try { + const apiBase = `${env.IMMICH_BASE_URL.replace(/\/+$/, "")}/api`; + const response = await fetch(`${apiBase}/server-info/ping`, { + headers: { "x-api-key": env.IMMICH_API_KEY }, + signal: AbortSignal.timeout(10_000), + }); + if (response.ok) { + report("IMMICH", { ok: true, detail: `Ping OK — ${apiBase}/server-info/ping` }); + } else { + report("IMMICH", { + ok: false, + detail: `HTTP ${response.status}${response.status === 401 || response.status === 403 ? " — API-Key ungültig?" : ""}`, + }); + } + } catch (error) { + report("IMMICH", { + ok: false, + detail: error instanceof Error ? error.message : String(error), + }); + } + + console.log(`${"─".repeat(48)}`); + console.log(`${failed === 0 ? "OK" : "FAIL"} ${failed === 0 ? "Alle Prüfungen bestanden." : `${failed} Prüfung(en) fehlgeschlagen.`}\n`); + + await pool.end(); + process.exit(failed === 0 ? 0 : 1); +} + +main().catch((error) => { + console.error("Preflight crashed:", error); + process.exit(1); +}); + +// ponytail: `db` is not imported here — preflight only needs `pool` for raw +// queries and `auth` for the adapter check. Keep the import surface minimal. \ No newline at end of file