From 268ea7544e0bf9ab0699547061291a7ba1d66e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Mon, 10 Aug 2026 23:06:13 +0200 Subject: [PATCH] fix: wire editorial approval, harden registration, set production auth URL - Wire admin approval UI to editorialService.approveEditorial so editorial accounts can move pending_approval -> active and log in. The approve button was permanently disabled and the service unreachable, so editorial users could never sign in. - Surface non-validation errors (e.g. SMTP failures) on the registration form instead of silently redirecting to the confirmation page. - Set BETTER_AUTH_URL default to the production domain in .env.example and compose.yaml so verification/reset links and the login origin check resolve against the live origin. - Add scripts/check-smtp.ts to verify SMTP connectivity against the configured transport. Co-Authored-By: Claude --- .env.example | 4 +- compose.yaml | 2 +- scripts/check-smtp.ts | 40 +++++++++ src/app/(public)/registrieren/page.tsx | 5 ++ .../admin/redaktionen/[id]/actions.test.ts | 82 +++++++++++++++++++ src/app/admin/redaktionen/[id]/actions.ts | 62 ++++++++++++++ src/modules/auth/public-forms.tsx | 2 + src/modules/editorials/admin-detail.tsx | 43 ++++++++-- 8 files changed, 228 insertions(+), 12 deletions(-) create mode 100644 scripts/check-smtp.ts create mode 100644 src/app/admin/redaktionen/[id]/actions.test.ts create mode 100644 src/app/admin/redaktionen/[id]/actions.ts diff --git a/.env.example b/.env.example index 278ead3..55b6083 100644 --- a/.env.example +++ b/.env.example @@ -1,9 +1,9 @@ # Portal database (separate from Immich) DATABASE_URL=postgres://portal:change-me@postgres:5432/portal -# Better Auth +# Better Auth — production public URL. For local dev, set http://localhost:3000 in .env BETTER_AUTH_SECRET=replace-with-a-long-random-secret -BETTER_AUTH_URL=http://localhost:3000 +BETTER_AUTH_URL=https://redaktionen.leon-tonhaeuser.de # Internal Immich API access; never expose these values to browsers IMMICH_BASE_URL=http://immich-server:2283 diff --git a/compose.yaml b/compose.yaml index 9e31033..2804876 100644 --- a/compose.yaml +++ b/compose.yaml @@ -28,7 +28,7 @@ services: environment: DATABASE_URL: ${DATABASE_URL:-postgres://portal:change-me@portal-db:5432/portal} BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET} - BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000} + BETTER_AUTH_URL: ${BETTER_AUTH_URL:-https://redaktionen.leon-tonhaeuser.de} IMMICH_BASE_URL: ${IMMICH_BASE_URL} IMMICH_API_KEY: ${IMMICH_API_KEY} SMTP_HOST: ${SMTP_HOST} diff --git a/scripts/check-smtp.ts b/scripts/check-smtp.ts new file mode 100644 index 0000000..b02e76a --- /dev/null +++ b/scripts/check-smtp.ts @@ -0,0 +1,40 @@ +import nodemailer from "nodemailer"; + +import { env } from "../src/config/env"; + +// Verifies the SMTP connection configured via env, and optionally sends a test mail. +// Run with production env: set -a; . ./.env; set +a; pnpm tsx scripts/check-smtp.ts [recipient] +async function main() { + const recipient = process.argv[2]; + + 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 }, + }); + + console.log( + `Verifying SMTP ${env.SMTP_HOST}:${env.SMTP_PORT} (secure=${env.SMTP_PORT === 465}) as ${env.SMTP_USER}, from=${env.SMTP_FROM} …`, + ); + + await transport.verify(); + console.log("OK: SMTP connection verified."); + + if (recipient) { + const info = await transport.sendMail({ + from: env.SMTP_FROM, + to: recipient, + subject: "Redaktionsportal — SMTP-Test", + text: "Test-E-Mail vom Redaktionsportal. Wenn diese ankommt, ist SMTP korrekt verbunden.", + }); + console.log(`OK: test mail sent to ${recipient} (messageId=${info.messageId}).`); + } +} + +main() + .then(() => process.exit(0)) + .catch((error) => { + console.error("FAILED: SMTP check failed:", error?.message ?? error); + process.exit(1); + }); \ No newline at end of file diff --git a/src/app/(public)/registrieren/page.tsx b/src/app/(public)/registrieren/page.tsx index fa79b03..1ce0b3b 100644 --- a/src/app/(public)/registrieren/page.tsx +++ b/src/app/(public)/registrieren/page.tsx @@ -67,6 +67,11 @@ async function registerAction( if (error instanceof RegistrationValidationError) { return { errors: { [error.field]: error.message } }; } + return { + errors: { + form: "Die Registrierung konnte nicht abgeschlossen werden. Bitte versuchen Sie es später erneut.", + }, + }; } redirect("/registrieren/bestaetigt"); diff --git a/src/app/admin/redaktionen/[id]/actions.test.ts b/src/app/admin/redaktionen/[id]/actions.test.ts new file mode 100644 index 0000000..54d2b4c --- /dev/null +++ b/src/app/admin/redaktionen/[id]/actions.test.ts @@ -0,0 +1,82 @@ +import { beforeEach, expect, test, vi } from "vitest"; + +beforeEach(() => { + vi.clearAllMocks(); +}); + +const mocks = vi.hoisted(() => ({ + approveEditorial: vi.fn(), + headers: vi.fn(), + requireAdmin: vi.fn(), + revalidatePath: vi.fn(), +})); + +vi.mock("next/headers", () => ({ headers: mocks.headers })); +vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath })); +vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin })); +vi.mock("@/modules/editorials/service", () => ({ + editorialService: { approveEditorial: mocks.approveEditorial }, + EditorialServiceError: class EditorialServiceError extends Error { + constructor(readonly code: string) { + super(code); + } + }, +})); + +import { approveEditorialAction } from "./actions"; + +test("the approve action rejects unauthenticated callers before touching the service", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED")); + const formData = new FormData(); + formData.set("priceEuros", "10.00"); + + await expect( + approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), + ).rejects.toThrow("ADMIN_REQUIRED"); + expect(mocks.approveEditorial).not.toHaveBeenCalled(); +}); + +test("the approve action forwards the authenticated principal and cents price to the service", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + mocks.approveEditorial.mockResolvedValue(undefined); + const formData = new FormData(); + formData.set("priceEuros", "12,50"); + + await approveEditorialAction("00000000-0000-4000-8000-000000000001", formData); + + expect(mocks.approveEditorial).toHaveBeenCalledWith({ + editorialId: "00000000-0000-4000-8000-000000000001", + priceCents: 1250, + adminUserId: "admin-1", + }); + expect(mocks.revalidatePath).toHaveBeenCalledWith( + "/admin/redaktionen/00000000-0000-4000-8000-000000000001", + ); +}); + +test("the approve action rejects a non-positive price before calling the service", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + const formData = new FormData(); + formData.set("priceEuros", "0"); + + await expect( + approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), + ).rejects.toThrow("Bitte geben Sie einen gültigen Nettopreis an."); + expect(mocks.approveEditorial).not.toHaveBeenCalled(); +}); + +test("the approve action translates a service error into a German message", async () => { + mocks.headers.mockResolvedValue(new Headers()); + mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" }); + const { EditorialServiceError } = await import("@/modules/editorials/service"); + mocks.approveEditorial.mockRejectedValue(new EditorialServiceError("ALBUM_GRANT_REQUIRED")); + const formData = new FormData(); + formData.set("priceEuros", "10.00"); + + await expect( + approveEditorialAction("00000000-0000-4000-8000-000000000001", formData), + ).rejects.toThrow("Bitte weisen Sie zuerst mindestens ein Album zu."); +}); \ No newline at end of file diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts new file mode 100644 index 0000000..daf57f2 --- /dev/null +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -0,0 +1,62 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { headers } from "next/headers"; + +import { requireAdmin } from "@/modules/auth/principal"; +import { editorialService, EditorialServiceError } from "@/modules/editorials/service"; + +export async function approveEditorialAction(editorialId: string, formData: FormData): Promise { + const principal = await requireAdmin(new Headers(await headers())); + const safeEditorialId = requiredId(editorialId); + const priceCents = parsePriceCents(formData.get("priceEuros")); + + try { + await editorialService.approveEditorial({ + editorialId: safeEditorialId, + priceCents, + adminUserId: principal.userId, + }); + } catch (error) { + throw new Error(approveErrorMessage(error)); + } + + revalidatePath(`/admin/redaktionen/${safeEditorialId}`); + revalidatePath(`/admin/redaktionen`); +} + +function parsePriceCents(value: unknown): number { + const euros = + typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN; + if (!Number.isFinite(euros) || euros <= 0) { + throw new Error("Bitte geben Sie einen gültigen Nettopreis an."); + } + return Math.round(euros * 100); +} + +function approveErrorMessage(error: unknown): string { + if (error instanceof EditorialServiceError) { + const messages: Record = { + INVALID_PRICE: "Bitte geben Sie einen gültigen Nettopreis an.", + EDITORIAL_NOT_FOUND: "Redaktion nicht gefunden.", + EMAIL_NOT_VERIFIED: "Die E-Mail-Adresse der Redaktion ist noch nicht bestätigt.", + ALBUM_GRANT_REQUIRED: "Bitte weisen Sie zuerst mindestens ein Album zu.", + INVALID_ACCOUNT_TRANSITION: + "Die Redaktion kann in ihrem aktuellen Status nicht freigegeben werden.", + APPROVAL_NOTICE_DELIVERY_UNKNOWN: + "Der Freigabe-Hinweis konnte nicht eindeutig zugeordnet werden.", + }; + return messages[error.code] ?? "Die Freigabe ist fehlgeschlagen."; + } + return "Die Freigabe ist fehlgeschlagen."; +} + +function requiredId(value: unknown): string { + if ( + typeof value !== "string" || + !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) + ) { + throw new Error("INVALID_ID"); + } + return value; +} \ No newline at end of file diff --git a/src/modules/auth/public-forms.tsx b/src/modules/auth/public-forms.tsx index 4accdaa..1f26ae3 100644 --- a/src/modules/auth/public-forms.tsx +++ b/src/modules/auth/public-forms.tsx @@ -7,6 +7,7 @@ import { authClient } from "./client"; export type RegistrationFormState = { errors?: Partial< Record< + | "form" | "companyName" | "contactName" | "email" @@ -47,6 +48,7 @@ export function RegistrationForm({ return (
+