Files
sass-mohfarawati/app/_admin/portfolio/actions.ts
T
moh dc21c33867 ADDED - Admin SEO page, robots/sitemap hardening and media/maintenance security fixes
SEO
- New Settings > SEO admin page (seo_settings in app_config): indexing switch,
  Google/Bing verification, X handle, JSON-LD identity (Person/Organization,
  sameAs), per-locale keywords, readiness checklist and open links for
  sitemap.xml / robots.txt / manifest.
- robots.txt is now dynamic: disallows admin, api, success and coming-soon
  paths; blocks everything while indexing is off or maintenance is on.
- sitemap.xml carries hreflang alternates per URL, lists only categories with
  published projects, and is empty while hidden.
- Metadata: robots + verification meta, og:locale in de_DE/en_US/ar_AR form,
  alternateLocale, twitter site/creator, project cover as OG image with
  article type, noindex on /success and /coming-soon.
- JSON-LD: WebSite + publisher graph on all public pages, CreativeWork per
  project (view-mode independent).

Security
- Maintenance bypass now requires a correctly signed admin cookie; the
  middleware previously only checked the cookie existed. Token helpers moved
  to lib/admin-session-token.ts (shared by proxy.ts and lib/admin-auth.ts).
- Media uploads: magic-byte validation against the declared type, SVG
  sanitization (script/handlers/foreignObject/javascript: rejected), upload
  folder sanitized, kind inferred from the real file.
- Media route: fixed prefix-based path check that accepted sibling
  directories, unknown extensions return 404, nosniff header, CSP sandbox on
  SVG, gif content type added.
- External media URLs: protocol-relative (//host) URLs rejected.

Portfolio
- Project and category slugs share /portfolio/[slug]; saving now rejects a
  slug already used on the other side instead of silently shadowing it.

Tooling/docs
- Lint: ignore scripts/legacy-prisma-seed.cjs, drop unused import.
- New docs/SEO.md; FEATURES, ARCHITECTURE (Drizzle instead of Prisma), admin
  spec and CLAUDE.md updated.
- Tests for all of the above (unit + integration); suite green.
2026-09-20 21:36:16 +02:00

650 lines
21 KiB
TypeScript

"use server";
import { eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { ZodError } from "zod";
import { routing } from "@/i18n/routing";
import { getAdminAppPath, toInternalAdminPath } from "@/lib/admin-routing";
import { withFlash } from "@/lib/admin-feedback";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { deleteEntityMediaUsages, replaceEntityMediaUsages } from "@/lib/media";
import { resolveMediaSelection } from "@/lib/media-service";
import { getLocalizedPath } from "@/lib/locale";
import { removeManagedMediaFile } from "@/lib/media-storage";
import { mediaFieldInputSchema } from "@/lib/media-validation";
import { db } from "@/lib/db";
import {
category,
mediaAsset,
mediaUsage,
portfolioAsset,
portfolioProject,
portfolioSection,
} from "@/lib/db/schema";
import { MediaUsageType } from "@/lib/db/enums";
import { isCheckedFormValue } from "@/lib/form-data";
import { getSiteSettings } from "@/lib/app-config";
import {
assetInputSchema,
categoryInputSchema,
projectDraftInputSchema,
projectInputSchema,
sectionInputSchema,
} from "@/lib/portfolio-validation";
/** Build a URL-safe slug from a title, falling back to a unique draft slug. */
function slugifyForDraft(input: string): string {
const base = input
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
return base || `draft-${Date.now()}`;
}
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect(getAdminAppPath("/"));
}
}
function getRedirectPath(formData: FormData, fallbackPath: string) {
return String(formData.get("redirectPath") ?? fallbackPath);
}
function normalizeCheckboxValue(formData: FormData, key: string) {
return isCheckedFormValue(formData.get(key));
}
function parseJsonArray(rawValue: FormDataEntryValue | null, key: string) {
if (typeof rawValue !== "string" || rawValue.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(rawValue);
if (!Array.isArray(parsed)) {
throw new Error(`${key} muss ein Array sein.`);
}
return parsed;
} catch {
throw new Error(`Ungueltige ${key} Nutzdaten.`);
}
}
function parseJsonObject(rawValue: FormDataEntryValue | null, key: string) {
if (typeof rawValue !== "string" || rawValue.trim() === "") {
return undefined;
}
try {
const parsed = JSON.parse(rawValue);
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
throw new Error(`${key} muss ein Objekt sein.`);
}
return parsed;
} catch {
throw new Error(`Ungueltige ${key} Nutzdaten.`);
}
}
function parseZodError(error: ZodError) {
return error.issues[0]?.message ?? "Validierung fehlgeschlagen.";
}
// Postgres unique-violation (code 23505, was Prisma's "P2002"). The error shape
// differs between drivers (postgres.js exposes `.code`; PGlite in tests nests it
// or only in the message), so check code, cause.code, and the message text.
function isUniqueViolation(error: unknown): boolean {
if (typeof error !== "object" || error === null) {
return false;
}
const e = error as { code?: string; cause?: { code?: string }; message?: string };
if (e.code === "23505" || e.cause?.code === "23505") {
return true;
}
return typeof e.message === "string" && /23505|duplicate key|unique constraint/i.test(e.message);
}
async function revalidatePortfolioPages() {
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/media"));
revalidatePath(toInternalAdminPath("/portfolio"));
revalidatePath(toInternalAdminPath("/portfolio/categories"));
revalidatePath(toInternalAdminPath("/portfolio/projects"));
revalidatePath("/portfolio");
const siteSettings = await getSiteSettings();
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, "/portfolio", siteSettings.defaultLocale));
}
}
async function removeManagedPaths(paths: string[]) {
for (const filePath of Array.from(new Set(paths.filter(Boolean)))) {
await removeManagedMediaFile(filePath);
}
}
export async function upsertCategoryAction(formData: FormData) {
await ensureAdmin();
const redirectPath = getRedirectPath(formData, getAdminAppPath("/portfolio/categories"));
try {
const parsed = categoryInputSchema.parse({
id: String(formData.get("id") ?? "").trim() || undefined,
slug: String(formData.get("slug") ?? ""),
nameAr: String(formData.get("nameAr") ?? ""),
nameEn: String(formData.get("nameEn") ?? ""),
nameDe: String(formData.get("nameDe") ?? ""),
descriptionAr: String(formData.get("descriptionAr") ?? ""),
descriptionEn: String(formData.get("descriptionEn") ?? ""),
descriptionDe: String(formData.get("descriptionDe") ?? ""),
sortOrder: String(formData.get("sortOrder") ?? "0"),
isActive: normalizeCheckboxValue(formData, "isActive"),
});
// Categories and projects share the public `/portfolio/[slug]` route, so a
// slug may only exist on one side. Categories win at resolve time, which
// would silently hide a project with the same slug.
const [projectWithSlug] = await db
.select({ id: portfolioProject.id })
.from(portfolioProject)
.where(eq(portfolioProject.slug, parsed.slug))
.limit(1);
if (projectWithSlug) {
throw new Error("Kategorie Slug ist bereits als Projekt Slug vergeben.");
}
if (parsed.id) {
await db.update(category).set(parsed).where(eq(category.id, parsed.id));
} else {
await db.insert(category).values(parsed);
}
await revalidatePortfolioPages();
redirect(withFlash(redirectPath, { success: "Kategorie gespeichert." }));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof ZodError
? parseZodError(error)
: isUniqueViolation(error)
? "Kategorie Slug muss eindeutig sein."
: error instanceof Error && error.message.includes("Slug")
? error.message
: "Kategorie konnte nicht gespeichert werden.";
redirect(withFlash(redirectPath, { error: message }));
}
}
export async function deleteCategoryAction(formData: FormData) {
await ensureAdmin();
const redirectPath = getRedirectPath(formData, getAdminAppPath("/portfolio/categories"));
const id = String(formData.get("id") ?? "");
try {
const projectCount = await db.$count(portfolioProject, eq(portfolioProject.categoryId, id));
if (projectCount > 0) {
redirect(withFlash(redirectPath, { error: "Kategorie mit Projekten kann nicht geloescht werden." }));
}
await db.delete(category).where(eq(category.id, id));
await revalidatePortfolioPages();
redirect(withFlash(redirectPath, { success: "Kategorie geloescht." }));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
redirect(withFlash(redirectPath, { error: "Kategorie konnte nicht geloescht werden." }));
}
}
export async function saveProjectAction(formData: FormData) {
await ensureAdmin();
const fallbackRedirect = String(formData.get("id") ?? "").trim()
? getAdminAppPath(`/portfolio/projects/${String(formData.get("id") ?? "").trim()}`)
: getAdminAppPath("/portfolio/projects/new");
const redirectPath = getRedirectPath(formData, fallbackRedirect);
const uploadedPaths: string[] = [];
const createdMediaAssetIds: string[] = [];
try {
const intent = String(formData.get("intent") ?? "save");
const isDraft = intent === "draft";
const parseSection = (section: Record<string, unknown>, index: number) =>
sectionInputSchema.parse({
...section,
media: section.media ? mediaFieldInputSchema.parse(section.media) : undefined,
sortOrder: section.sortOrder ?? index,
});
const parseAsset = (asset: Record<string, unknown>, index: number) =>
assetInputSchema.parse({
...asset,
media: asset.media ? mediaFieldInputSchema.parse(asset.media) : undefined,
sortOrder: asset.sortOrder ?? index,
});
// A draft keeps only the entries that are already valid; a full save
// validates every entry strictly.
const sections = parseJsonArray(formData.get("sections"), "sections").flatMap((section, index) => {
if (!isDraft) {
return [parseSection(section, index)];
}
try {
return [parseSection(section, index)];
} catch {
return [];
}
});
const assets = parseJsonArray(formData.get("assets"), "assets").flatMap((asset, index) => {
if (!isDraft) {
return [parseAsset(asset, index)];
}
try {
return [parseAsset(asset, index)];
} catch {
return [];
}
});
const coverMedia = parseJsonObject(formData.get("coverMedia"), "coverMedia");
const rawSlug = String(formData.get("slug") ?? "").trim();
const slug =
isDraft && !rawSlug
? slugifyForDraft(
String(formData.get("titleDe") ?? "") ||
String(formData.get("titleEn") ?? "") ||
String(formData.get("titleAr") ?? ""),
)
: rawSlug;
const rawYear = String(formData.get("projectYear") ?? "").trim();
const projectYear = isDraft && !rawYear ? String(new Date().getFullYear()) : rawYear;
const parsed = (isDraft ? projectDraftInputSchema : projectInputSchema).parse({
id: String(formData.get("id") ?? "").trim() || undefined,
categoryId: String(formData.get("categoryId") ?? ""),
slug,
viewMode: String(formData.get("viewMode") ?? "GRID"),
titleAr: String(formData.get("titleAr") ?? ""),
titleEn: String(formData.get("titleEn") ?? ""),
titleDe: String(formData.get("titleDe") ?? ""),
summaryAr: String(formData.get("summaryAr") ?? ""),
summaryEn: String(formData.get("summaryEn") ?? ""),
summaryDe: String(formData.get("summaryDe") ?? ""),
clientName: String(formData.get("clientName") ?? ""),
projectYear,
serviceLabelAr: String(formData.get("serviceLabelAr") ?? ""),
serviceLabelEn: String(formData.get("serviceLabelEn") ?? ""),
serviceLabelDe: String(formData.get("serviceLabelDe") ?? ""),
previewUrl: String(formData.get("previewUrl") ?? ""),
currentCoverImagePath: String(formData.get("currentCoverImagePath") ?? ""),
coverMedia: coverMedia ? mediaFieldInputSchema.parse(coverMedia) : undefined,
sortOrder: String(formData.get("sortOrder") ?? "0"),
isFeatured: normalizeCheckboxValue(formData, "isFeatured"),
isPublished: isDraft ? false : normalizeCheckboxValue(formData, "isPublished"),
sections,
assets,
});
const [categoryWithSlug] = await db
.select({ id: category.id })
.from(category)
.where(eq(category.slug, parsed.slug))
.limit(1);
if (categoryWithSlug) {
throw new Error("Projekt Slug ist bereits als Kategorie Slug vergeben.");
}
const existingProject = parsed.id
? (
await db
.select({
isPublished: portfolioProject.isPublished,
publishedAt: portfolioProject.publishedAt,
})
.from(portfolioProject)
.where(eq(portfolioProject.id, parsed.id))
.limit(1)
)[0] ?? null
: null;
const shouldPublishNow = parsed.isPublished && !existingProject?.publishedAt;
const coverSelection = await resolveMediaSelection({
media: parsed.coverMedia,
uploadFile: formData.get("coverFile"),
folder: "covers",
fallbackLabel: parsed.titleDe || parsed.titleEn || parsed.titleAr || parsed.slug,
required: false,
});
if (coverSelection.createdAssetId) {
createdMediaAssetIds.push(coverSelection.createdAssetId);
}
if (coverSelection.uploadedUrl) {
uploadedPaths.push(coverSelection.uploadedUrl);
}
const sectionRows: Array<{
type: (typeof parsed.sections)[number]["type"];
titleAr: string;
titleEn: string;
titleDe: string;
bodyAr: string;
bodyEn: string;
bodyDe: string;
imagePath: string | null;
imageAssetId: string | null;
linkUrl: string | null;
sortOrder: number;
}> = [];
for (let index = 0; index < parsed.sections.length; index += 1) {
const section = parsed.sections[index];
const sectionSelection = await resolveMediaSelection({
media: section.media,
uploadFile: formData.get(`section-image-upload-${index}`),
folder: "sections",
fallbackLabel: section.titleDe || section.titleEn || section.titleAr || `section-${index + 1}`,
required: false,
});
if (sectionSelection.createdAssetId) {
createdMediaAssetIds.push(sectionSelection.createdAssetId);
}
if (sectionSelection.uploadedUrl) {
uploadedPaths.push(sectionSelection.uploadedUrl);
}
sectionRows.push({
type: section.type,
titleAr: section.titleAr,
titleEn: section.titleEn,
titleDe: section.titleDe,
bodyAr: section.bodyAr,
bodyEn: section.bodyEn,
bodyDe: section.bodyDe,
imagePath: sectionSelection.url || null,
imageAssetId: sectionSelection.assetId,
linkUrl: section.linkUrl || null,
sortOrder: index,
});
}
const assetRows: Array<{
kind: (typeof parsed.assets)[number]["kind"];
filePath: string;
mediaAssetId: string | null;
altAr: string;
altEn: string;
altDe: string;
sortOrder: number;
}> = [];
for (let index = 0; index < parsed.assets.length; index += 1) {
const asset = parsed.assets[index];
const assetSelection = await resolveMediaSelection({
media: asset.media,
uploadFile: asset.fileFieldName ? formData.get(asset.fileFieldName) : null,
folder: "assets",
fallbackLabel: asset.altDe || asset.altEn || asset.altAr || `asset-${index + 1}`,
required: true,
});
if (!assetSelection.url) {
throw new Error("Jede Datei Zeile braucht eine vorhandene Datei oder einen neuen Upload.");
}
if (assetSelection.createdAssetId) {
createdMediaAssetIds.push(assetSelection.createdAssetId);
}
if (assetSelection.uploadedUrl) {
uploadedPaths.push(assetSelection.uploadedUrl);
}
assetRows.push({
kind: asset.kind,
filePath: assetSelection.url,
mediaAssetId: assetSelection.assetId,
altAr: asset.altAr,
altEn: asset.altEn,
altDe: asset.altDe,
sortOrder: index,
});
}
const projectResult = await db.transaction(async (tx) => {
const projectValues = {
categoryId: parsed.categoryId,
slug: parsed.slug,
viewMode: parsed.viewMode,
titleAr: parsed.titleAr,
titleEn: parsed.titleEn,
titleDe: parsed.titleDe,
summaryAr: parsed.summaryAr,
summaryEn: parsed.summaryEn,
summaryDe: parsed.summaryDe,
clientName: parsed.clientName,
projectYear: parsed.projectYear,
serviceLabelAr: parsed.serviceLabelAr,
serviceLabelEn: parsed.serviceLabelEn,
serviceLabelDe: parsed.serviceLabelDe,
previewUrl: parsed.previewUrl || null,
coverImagePath: coverSelection.url || null,
isFeatured: parsed.isFeatured,
isPublished: parsed.isPublished,
sortOrder: parsed.sortOrder,
};
const [currentProject] = parsed.id
? await tx
.update(portfolioProject)
.set({
...projectValues,
publishedAt: parsed.isPublished
? shouldPublishNow
? new Date()
: existingProject?.publishedAt ?? new Date()
: null,
})
.where(eq(portfolioProject.id, parsed.id))
.returning()
: await tx
.insert(portfolioProject)
.values({ ...projectValues, publishedAt: parsed.isPublished ? new Date() : null })
.returning();
await tx.delete(portfolioSection).where(eq(portfolioSection.projectId, currentProject.id));
await tx.delete(portfolioAsset).where(eq(portfolioAsset.projectId, currentProject.id));
const createdSections = [];
for (const section of sectionRows) {
const [createdSection] = await tx
.insert(portfolioSection)
.values({
projectId: currentProject.id,
type: section.type,
titleAr: section.titleAr,
titleEn: section.titleEn,
titleDe: section.titleDe,
bodyAr: section.bodyAr,
bodyEn: section.bodyEn,
bodyDe: section.bodyDe,
imagePath: section.imagePath || null,
linkUrl: section.linkUrl || null,
sortOrder: section.sortOrder,
})
.returning();
createdSections.push(createdSection);
}
const createdAssets = [];
for (const asset of assetRows) {
const [createdAsset] = await tx
.insert(portfolioAsset)
.values({
projectId: currentProject.id,
kind: asset.kind,
filePath: asset.filePath,
altAr: asset.altAr,
altEn: asset.altEn,
altDe: asset.altDe,
sortOrder: asset.sortOrder,
})
.returning();
createdAssets.push(createdAsset);
}
return {
project: currentProject,
createdSections,
createdAssets,
};
});
await replaceEntityMediaUsages({
entityType: "portfolio-project",
entityId: projectResult.project.id,
usages: [
...(coverSelection.assetId
? [
{
assetId: coverSelection.assetId,
usageType: MediaUsageType.PORTFOLIO_COVER,
fieldKey: "cover",
},
]
: []),
...projectResult.createdSections.flatMap((section, index) =>
sectionRows[index]?.imageAssetId
? [
{
assetId: sectionRows[index].imageAssetId as string,
usageType: MediaUsageType.PORTFOLIO_SECTION,
fieldKey: section.id,
},
]
: [],
),
...projectResult.createdAssets.flatMap((asset, index) =>
assetRows[index]?.mediaAssetId
? [
{
assetId: assetRows[index].mediaAssetId as string,
usageType: MediaUsageType.PORTFOLIO_ASSET,
fieldKey: asset.id,
},
]
: [],
),
],
});
await revalidatePortfolioPages();
revalidatePath(toInternalAdminPath(`/portfolio/projects/${projectResult.project.id}`));
revalidatePath(`/portfolio/${projectResult.project.slug}`);
const siteSettings = await getSiteSettings();
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, `/portfolio/${projectResult.project.slug}`, siteSettings.defaultLocale));
}
redirect(
withFlash(getAdminAppPath(`/portfolio/projects/${projectResult.project.id}`), {
success: "Projekt gespeichert.",
}),
);
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof ZodError
? parseZodError(error)
: isUniqueViolation(error)
? "Projekt Slug muss eindeutig sein."
: error instanceof Error
? error.message
: "Projekt konnte nicht gespeichert werden.";
await removeManagedPaths(uploadedPaths);
if (createdMediaAssetIds.length > 0) {
await db.delete(mediaUsage).where(inArray(mediaUsage.assetId, createdMediaAssetIds));
await db.delete(mediaAsset).where(inArray(mediaAsset.id, createdMediaAssetIds));
}
redirect(withFlash(redirectPath, { error: message }));
}
}
export async function deleteProjectAction(formData: FormData) {
await ensureAdmin();
const id = String(formData.get("id") ?? "");
try {
const [project] = await db
.select({ slug: portfolioProject.slug })
.from(portfolioProject)
.where(eq(portfolioProject.id, id))
.limit(1);
if (!project) {
redirect(withFlash(getAdminAppPath("/portfolio"), { error: "Projekt nicht gefunden." }));
}
await db.delete(portfolioProject).where(eq(portfolioProject.id, id));
await deleteEntityMediaUsages("portfolio-project", id);
await revalidatePortfolioPages();
revalidatePath(`/portfolio/${project.slug}`);
const siteSettings = await getSiteSettings();
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, `/portfolio/${project.slug}`, siteSettings.defaultLocale));
}
redirect(withFlash(getAdminAppPath("/portfolio"), { success: "Projekt geloescht." }));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
redirect(withFlash(getAdminAppPath("/portfolio"), { error: "Projekt konnte nicht geloescht werden." }));
}
}