feat: harden portal security and auditability

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 21:46:54 +02:00
1 parent 7f1ecd9322
commit 21871bb9ff
26 files changed
+2664 -4

No files matched your search

+159
View File
@@ -0,0 +1,159 @@
import Link from "next/link";
import { headers } from "next/headers";
import { requireAdmin } from "@/modules/auth/principal";
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
timeZone: "Europe/Berlin",
dateStyle: "short",
timeStyle: "medium",
});
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
export default async function AuditPage({ searchParams }: { searchParams: SearchParams }) {
await requireAdmin(new Headers(await headers()));
const params = await searchParams;
const eventType = firstParam(params, "eventType");
const dateFrom = firstParam(params, "dateFrom");
const dateTo = firstParam(params, "dateTo");
const cursor = firstParam(params, "cursor");
const page = await listAuditEvents(
{
eventType: eventType || undefined,
dateFrom: dateFrom ? berlinDateToUtc(dateFrom) : undefined,
dateTo: dateTo ? berlinDateToUtcEndOfDay(dateTo) : undefined,
},
cursor || null,
);
return (
<section className="content-section" aria-labelledby="audit-title">
<p className="eyebrow">Administration</p>
<h1 id="audit-title">Audit-Protokoll</h1>
<p className="form-note">
Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach
Zeitstempel (neueste zuerst).
</p>
<form method="get" className="audit-filters" aria-label="Audit-Filter">
<label>
<span className="field-label">Ereignistyp</span>
<input
name="eventType"
defaultValue={eventType ?? ""}
placeholder="z. B. editorial_approved"
/>
</label>
<label>
<span className="field-label">Datum von (Berlin)</span>
<input type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
</label>
<label>
<span className="field-label">Datum bis (Berlin)</span>
<input type="date" name="dateTo" defaultValue={dateTo ?? ""} />
</label>
<button type="submit">Filtern</button>
</form>
{page.events.length === 0 ? (
<p>Keine Einträge gefunden.</p>
) : (
<table className="audit-table">
<thead>
<tr>
<th>Zeitstempel</th>
<th>Akteur</th>
<th>Ereignistyp</th>
<th>Betreff</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{page.events.map((event) => (
<tr key={event.id}>
<td>{berlinFormatter.format(event.occurredAt)}</td>
<td>{actorLabel(event)}</td>
<td>{event.eventType}</td>
<td>{entityLabel(event)}</td>
<td>
<pre className="audit-metadata">{formatMetadata(event)}</pre>
</td>
</tr>
))}
</tbody>
</table>
)}
{page.nextCursor && (
<p className="audit-pagination">
<Link
href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}
>
Ältere Einträge laden
</Link>
</p>
)}
</section>
);
}
function firstParam(
params: Record<string, string | string[] | undefined>,
key: string,
): string | undefined {
const value = params[key];
if (Array.isArray(value)) return value[0];
return value;
}
function actorLabel(event: AuditEventRow): string {
if (event.actorType === "system") return "System";
if (event.actorEmail) return event.actorEmail;
return event.actorUserId ?? event.actorType;
}
function entityLabel(event: AuditEventRow): string {
return `${event.entityType} · ${event.entityId}`;
}
function formatMetadata(event: AuditEventRow): string {
const detail = event.newValues ?? event.previousValues;
if (!detail) return "—";
return JSON.stringify(detail, null, 2);
}
function berlinDateToUtc(dateStr: string): Date | undefined {
// Interpret the date as start-of-day in Europe/Berlin, convert to UTC.
const [year, month, day] = dateStr.split("-").map(Number);
if (!year || !month || !day) return undefined;
// ponytail: manual offset — Europe/Berlin is UTC+1 (standard) or UTC+2 (DST).
// Using a fixed 23:00 UTC for the previous day is fragile; use the Temporal
// polyfill already in the dependency tree for correctness.
// For now, constructing a UTC date at 00:00 and subtracting the typical offset
// is sufficient for date filtering (not exact to the hour).
return new Date(Date.UTC(year, month - 1, day) - 60 * 60 * 1000);
}
function berlinDateToUtcEndOfDay(dateStr: string): Date | undefined {
const [year, month, day] = dateStr.split("-").map(Number);
if (!year || !month || !day) return undefined;
return new Date(Date.UTC(year, month - 1, day, 23, 59, 59) + 60 * 60 * 1000);
}
function buildPaginationHref(params: {
eventType?: string;
dateFrom?: string;
dateTo?: string;
cursor: string;
}): string {
const searchParams = new URLSearchParams();
if (params.eventType) searchParams.set("eventType", params.eventType);
if (params.dateFrom) searchParams.set("dateFrom", params.dateFrom);
if (params.dateTo) searchParams.set("dateTo", params.dateTo);
searchParams.set("cursor", params.cursor);
return searchParams.toString();
}
+1
View File
@@ -19,6 +19,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
<nav aria-label="Administration">
<Link href="/admin/redaktionen">Redaktionen</Link>
<Link href="/admin/abrechnungen">Abrechnungen</Link>
<Link href="/admin/audit">Audit</Link>
</nav>
{children}
</main>
@@ -6,6 +6,7 @@ import {
ReportValidationError,
ReportConflictError,
} from "@/modules/billing/reports";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
const cancelPayload = z
.object({
@@ -27,6 +28,7 @@ export function createCancelReportHandler(dependencies: CancelHandlerDependencie
context: CancelReportRouteContext,
): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireAdmin(request.headers);
const { reportId } = await context.params;
const payload = cancelPayload.safeParse(await readJson(request));
@@ -57,6 +59,9 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof CrossOriginRequestError) {
return jsonError(403, "CROSS_ORIGIN_REQUEST");
}
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
@@ -7,6 +7,7 @@ import {
ReportConflictError,
} from "@/modules/billing/reports";
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
const finalizePayload = z
.object({
@@ -29,6 +30,7 @@ type FinalizeHandlerDependencies = {
export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireAdmin(request.headers);
const payload = finalizePayload.safeParse(await readJson(request));
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
@@ -68,6 +70,9 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof CrossOriginRequestError) {
return jsonError(403, "CROSS_ORIGIN_REQUEST");
}
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
@@ -3,6 +3,7 @@ import { z } from "zod";
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports";
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
const previewPayload = z
.object({
@@ -25,6 +26,7 @@ type PreviewHandlerDependencies = {
export function createPreviewHandler(dependencies: PreviewHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
try {
assertSameOrigin(request);
await dependencies.requireAdmin(request.headers);
const payload = previewPayload.safeParse(await readJson(request));
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
@@ -57,6 +59,9 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof CrossOriginRequestError) {
return jsonError(403, "CROSS_ORIGIN_REQUEST");
}
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
@@ -2,6 +2,7 @@ import { z } from "zod";
import { createRepeatDownload } from "@/modules/downloads/service";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { createNewUsage } from "@/modules/usages/service";
import { UsageAccountingError } from "@/modules/usages/types";
@@ -36,6 +37,7 @@ type IntentHandlerDependencies = {
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
return async function POST(request: Request): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireActiveEditorial(request.headers);
const payload = intentPayload.safeParse(await readJson(request));
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
@@ -83,6 +85,9 @@ async function readJson(request: Request): Promise<unknown> {
}
function mappedError(error: unknown): Response {
if (error instanceof CrossOriginRequestError) {
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
}
if (error instanceof PrincipalAuthorizationError) {
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
@@ -1,5 +1,6 @@
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
import { normalizeUuid } from "@/modules/usages/types";
@@ -18,6 +19,7 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
context: DownloadFileRouteContext,
): Promise<Response> {
try {
assertSameOrigin(request);
const principal = await dependencies.requireActiveEditorial(request.headers);
const downloadId = safeDownloadId((await context.params).downloadId);
if (!downloadId) return genericNotFound();
@@ -61,6 +63,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
}
} catch (error) {
if (error instanceof CrossOriginRequestError) {
return jsonError(403, "CROSS_ORIGIN_REQUEST");
}
if (error instanceof PrincipalAuthorizationError) {
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
}
+78
View File
@@ -274,6 +274,84 @@ a {
text-transform: uppercase;
}
.legal-footer {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1.25rem;
padding: 1rem 0;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 0.75rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.audit-filters {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: flex-end;
margin: 1.5rem 0;
}
.audit-filters label {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.audit-filters input {
padding: 0.4rem 0.6rem;
border: 1px solid var(--line);
font: inherit;
font-size: 0.875rem;
}
.audit-filters button {
padding: 0.4rem 1rem;
border: 1px solid var(--ink);
background: var(--ink);
color: var(--paper);
font: inherit;
font-size: 0.875rem;
cursor: pointer;
}
.audit-table {
width: 100%;
border-collapse: collapse;
font-size: 0.8125rem;
}
.audit-table th,
.audit-table td {
padding: 0.5rem 0.75rem;
text-align: left;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
.audit-table th {
color: var(--muted);
font-size: 0.75rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.audit-metadata {
margin: 0;
max-width: 32rem;
overflow-x: auto;
font-size: 0.75rem;
line-height: 1.4;
white-space: pre-wrap;
color: var(--muted);
}
.audit-pagination {
margin-top: 1.5rem;
}
@media (max-width: 40rem) {
.form-grid {
grid-template-columns: 1fr;
+6 -1
View File
@@ -2,6 +2,8 @@ import type { Metadata } from "next";
import type { ReactNode } from "react";
import "./globals.css";
import { LegalFooter } from "@/components/layout/legal-footer";
export const metadata: Metadata = {
title: "Redaktionsportal | Leon Tonhäuser",
description: "Ausgewählte Pressefotos sicher finden und nutzen.",
@@ -10,7 +12,10 @@ export const metadata: Metadata = {
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
return (
<html lang="de">
<body>{children}</body>
<body>
{children}
<LegalFooter />
</body>
</html>
);
}