Files
immich-redaktions-plugin/src/app/admin/redaktionen/[id]/actions.ts
T
Leon Tonhäuser 0d939593c8 feat: enforce admin 2FA, step-up auth, stronger password policy
Implements OWASP audit recommendations P1-P3:

P1 - Two-factor authentication (TOTP) mandatory for admins:
- better-auth twoFactor plugin; new two_factor table + user flag
  (migration 0010, MUST run before deploying the app)
- requireAdmin throws TWO_FACTOR_REQUIRED without a finished setup;
  pages redirect to the new /zwei-faktor wizard which uses a weak
  guard (allowWithoutTwoFactor) so admins can never lock themselves
  out. Wizard lives outside /admin to avoid layout redirect loops.
- login flow handles twoFactorRedirect and asks for the TOTP code;
  backup codes are shown once during enablement

P2 - Step-up for destructive operations (ASVS 2.5.4):
- hardDeleteEditorialAction and resetUsageDataAction reject sessions
  older than 15 minutes (SESSION_STALE) with actionable German
  messages instead of throwing opaque digests

P3 - Password policy (NIST 800-63B):
- minimum length raised from 8 to 12 plus common-password denylist,
  enforced for registration AND reset/change via a before-hook
2026-08-25 02:30:58 +02:00

243 lines
8.3 KiB
TypeScript

"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { eq } from "drizzle-orm";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { requireAdmin, PrincipalAuthorizationError, DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS } from "@/modules/auth/principal";
import { editorialService, EditorialServiceError } from "@/modules/editorials/service";
// Returned to the client form so failures surface as inline German text
// instead of an opaque Next.js error-digest page (a thrown server action
// becomes a 500 with a digest the user can't read).
export type ApproveActionResult = { ok: boolean; message: string };
const INITIAL_RESULT: ApproveActionResult = { ok: true, message: "" };
export async function approveEditorialAction(
editorialId: string,
_prevState: ApproveActionResult,
formData: FormData,
): Promise<ApproveActionResult> {
const principal = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const price = parsePriceCents(formData.get("priceEuros"));
if (!price.ok) {
return { ok: false, message: price.message };
}
try {
await editorialService.approveEditorial({
editorialId: safeEditorialId,
priceCents: price.cents,
adminUserId: principal.userId,
});
} catch (error) {
return { ok: false, message: approveErrorMessage(error) };
}
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
revalidatePath(`/admin/redaktionen`);
return INITIAL_RESULT;
}
export async function archiveEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.archiveEditorial({
editorialId,
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
revalidatePath("/admin/redaktionen");
redirect("/admin/redaktionen");
}
export async function unarchiveEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.unarchiveEditorial({
editorialId,
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
revalidatePath("/admin/redaktionen");
}
export type ResetUsageResult = { ok: boolean; message: string };
/**
* Step-up guard for irreversible operations (OWASP ASVS 2.5.4): the session
* must be recent, otherwise the admin re-authenticates first.
*/
async function freshAdminPrincipal(): Promise<
Awaited<ReturnType<typeof requireAdmin>> | ResetUsageResult
> {
try {
return await requireAdmin(new Headers(await headers()), {
maxSessionAgeSeconds: DESTRUCTIVE_ACTION_MAX_SESSION_AGE_SECONDS,
});
} catch (error) {
if (error instanceof PrincipalAuthorizationError) {
return { ok: false, message: adminGuardMessage(error.code) };
}
throw error;
}
}
function adminGuardMessage(code: PrincipalAuthorizationError["code"]): string {
switch (code) {
case "SESSION_STALE":
return "Aus Sicherheitsgründen ist Ihre Sitzung zu alt für diese Aktion. Bitte melden Sie sich erneut an und wiederholen Sie den Schritt.";
case "TWO_FACTOR_REQUIRED":
return "Für diese Aktion ist Zwei-Faktor-Authentifizierung erforderlich.";
default:
return "Die Aktion ist fehlgeschlagen.";
}
}
function isPrincipal(result: unknown): result is Awaited<ReturnType<typeof requireAdmin>> {
return typeof result === "object" && result !== null && "userId" in result;
}
export async function hardDeleteEditorialAction(editorialId: string): Promise<ResetUsageResult> {
const safeEditorialId = requiredId(editorialId);
const principal = await freshAdminPrincipal();
if (!isPrincipal(principal)) {
return principal;
}
await editorialService.hardDeleteEditorial(safeEditorialId);
revalidatePath("/admin/redaktionen");
redirect("/admin/redaktionen");
}
export async function resetUsageDataAction(editorialId: string): Promise<ResetUsageResult> {
const safeEditorialId = requiredId(editorialId);
const principal = await freshAdminPrincipal();
if (!isPrincipal(principal)) {
return principal;
}
try {
const result = await editorialService.resetUsageData({
editorialId: safeEditorialId,
adminUserId: principal.userId,
});
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
revalidatePath("/admin/redaktionen");
revalidatePath("/admin");
revalidatePath("/admin/abrechnungen");
return {
ok: true,
message: `${result.deletedUsages} Nutzung(en) und ${result.deletedReports} Abrechnung(en) gelöscht.`,
};
} catch (error) {
if (error instanceof EditorialServiceError && error.code === "EDITORIAL_NOT_FOUND") {
return { ok: false, message: "Redaktion nicht gefunden." };
}
console.error("Failed to reset usage data:", error);
return { ok: false, message: "Das Zurücksetzen ist fehlgeschlagen." };
}
}
export async function suspendEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.transitionEditorialStatus({
editorialId,
from: "active",
to: "suspended",
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
}
export async function reactivateEditorialAction(editorialId: string): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
await editorialService.transitionEditorialStatus({
editorialId,
from: "suspended",
to: "active",
adminUserId: admin.userId,
});
revalidatePath(`/admin/redaktionen/${editorialId}`);
}
export async function updateFlatrateAction(editorialId: string, formData: FormData): Promise<void> {
const admin = await requireAdmin(new Headers(await headers()));
const safeEditorialId = requiredId(editorialId);
const flatrateActive = formData.get("flatrateActive") === "on";
let flatratePriceCents: number | null = null;
const rawPrice = formData.get("flatratePriceEuros");
if (rawPrice && typeof rawPrice === "string" && rawPrice.trim() !== "") {
const price = parsePriceCents(rawPrice);
if (price.ok) {
flatratePriceCents = price.cents;
}
}
if (flatrateActive && flatratePriceCents === null) {
throw new Error("INVALID_FLATRATE_PRICE");
}
let flatrateAssetLimit: number | null = null;
const rawLimit = formData.get("flatrateAssetLimit");
if (rawLimit && typeof rawLimit === "string" && rawLimit.trim() !== "") {
const limit = parseInt(rawLimit, 10);
if (Number.isFinite(limit) && limit >= 1) {
flatrateAssetLimit = limit;
}
}
await db
.update(editorialAccounts)
.set({
flatrateActive,
flatratePriceCents,
flatrateAssetLimit,
})
.where(eq(editorialAccounts.id, safeEditorialId));
revalidatePath(`/admin/redaktionen/${safeEditorialId}`);
}
function parsePriceCents(
value: unknown,
): { ok: true; cents: number } | { ok: false; message: string } {
const euros =
typeof value === "string" ? Number.parseFloat(value.replace(",", ".")) : Number.NaN;
if (!Number.isFinite(euros) || euros <= 0) {
return { ok: false, message: "Bitte geben Sie einen gültigen Nettopreis an." };
}
return { ok: true, cents: Math.round(euros * 100) };
}
function approveErrorMessage(error: unknown): string {
if (error instanceof EditorialServiceError) {
const messages: Record<string, string> = {
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;
}