feat: harden portal security and auditability
This commit is contained in:
1 parent
7f1ecd9322
commit
21871bb9ff
26 files changed
+2664
-4
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE "rate_limits" (
|
||||||
|
"key" text NOT NULL,
|
||||||
|
"window_boundary" integer NOT NULL,
|
||||||
|
"count" integer DEFAULT 1 NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "rate_limits_key_window_boundary_pk" PRIMARY KEY("key","window_boundary")
|
||||||
|
);
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -36,6 +36,13 @@
|
|||||||
"when": 1786363479515,
|
"when": 1786363479515,
|
||||||
"tag": "0004_download_history_indexes",
|
"tag": "0004_download_history_indexes",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 5,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786379282947,
|
||||||
|
"tag": "0005_rate_limits",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+48
-1
@@ -3,6 +3,53 @@ import type { NextConfig } from "next";
|
|||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
poweredByHeader: false,
|
poweredByHeader: false,
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: "/(.*)",
|
||||||
|
headers: [
|
||||||
|
{
|
||||||
|
key: "Content-Security-Policy",
|
||||||
|
// ponytail: restrictive CSP — 'unsafe-inline' for styles only
|
||||||
|
// because Next.js injects inline styles. No unsafe-inline for
|
||||||
|
// scripts. Upgrade path: nonces once Next supports them per-route.
|
||||||
|
value: [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
].join("; "),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Referrer-Policy",
|
||||||
|
value: "strict-origin-when-cross-origin",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Content-Type-Options",
|
||||||
|
value: "nosniff",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Frame-Options",
|
||||||
|
value: "DENY",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Permissions-Policy",
|
||||||
|
value: [
|
||||||
|
"camera=()",
|
||||||
|
"microphone=()",
|
||||||
|
"geolocation=()",
|
||||||
|
"interest-cohort=()",
|
||||||
|
].join(", "),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build",
|
"build": "NEXT_DISABLE_TURBOPACK=1 next build --webpack",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
|
|||||||
<nav aria-label="Administration">
|
<nav aria-label="Administration">
|
||||||
<Link href="/admin/redaktionen">Redaktionen</Link>
|
<Link href="/admin/redaktionen">Redaktionen</Link>
|
||||||
<Link href="/admin/abrechnungen">Abrechnungen</Link>
|
<Link href="/admin/abrechnungen">Abrechnungen</Link>
|
||||||
|
<Link href="/admin/audit">Audit</Link>
|
||||||
</nav>
|
</nav>
|
||||||
{children}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
ReportValidationError,
|
ReportValidationError,
|
||||||
ReportConflictError,
|
ReportConflictError,
|
||||||
} from "@/modules/billing/reports";
|
} from "@/modules/billing/reports";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
const cancelPayload = z
|
const cancelPayload = z
|
||||||
.object({
|
.object({
|
||||||
@@ -27,6 +28,7 @@ export function createCancelReportHandler(dependencies: CancelHandlerDependencie
|
|||||||
context: CancelReportRouteContext,
|
context: CancelReportRouteContext,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
const principal = await dependencies.requireAdmin(request.headers);
|
const principal = await dependencies.requireAdmin(request.headers);
|
||||||
const { reportId } = await context.params;
|
const { reportId } = await context.params;
|
||||||
const payload = cancelPayload.safeParse(await readJson(request));
|
const payload = cancelPayload.safeParse(await readJson(request));
|
||||||
@@ -57,6 +59,9 @@ async function readJson(request: Request): Promise<unknown> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function mappedError(error: unknown): Response {
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
if (error instanceof PrincipalAuthorizationError) {
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
ReportConflictError,
|
ReportConflictError,
|
||||||
} from "@/modules/billing/reports";
|
} from "@/modules/billing/reports";
|
||||||
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
const finalizePayload = z
|
const finalizePayload = z
|
||||||
.object({
|
.object({
|
||||||
@@ -29,6 +30,7 @@ type FinalizeHandlerDependencies = {
|
|||||||
export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) {
|
export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) {
|
||||||
return async function POST(request: Request): Promise<Response> {
|
return async function POST(request: Request): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
const principal = await dependencies.requireAdmin(request.headers);
|
const principal = await dependencies.requireAdmin(request.headers);
|
||||||
const payload = finalizePayload.safeParse(await readJson(request));
|
const payload = finalizePayload.safeParse(await readJson(request));
|
||||||
if (!payload.success) return jsonError(400, "INVALID_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 {
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
if (error instanceof PrincipalAuthorizationError) {
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
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 { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports";
|
import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports";
|
||||||
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
const previewPayload = z
|
const previewPayload = z
|
||||||
.object({
|
.object({
|
||||||
@@ -25,6 +26,7 @@ type PreviewHandlerDependencies = {
|
|||||||
export function createPreviewHandler(dependencies: PreviewHandlerDependencies) {
|
export function createPreviewHandler(dependencies: PreviewHandlerDependencies) {
|
||||||
return async function POST(request: Request): Promise<Response> {
|
return async function POST(request: Request): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
await dependencies.requireAdmin(request.headers);
|
await dependencies.requireAdmin(request.headers);
|
||||||
const payload = previewPayload.safeParse(await readJson(request));
|
const payload = previewPayload.safeParse(await readJson(request));
|
||||||
if (!payload.success) return jsonError(400, "INVALID_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 {
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
if (error instanceof PrincipalAuthorizationError) {
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
|||||||
|
|
||||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
import { createNewUsage } from "@/modules/usages/service";
|
import { createNewUsage } from "@/modules/usages/service";
|
||||||
import { UsageAccountingError } from "@/modules/usages/types";
|
import { UsageAccountingError } from "@/modules/usages/types";
|
||||||
|
|
||||||
@@ -36,6 +37,7 @@ type IntentHandlerDependencies = {
|
|||||||
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||||
return async function POST(request: Request): Promise<Response> {
|
return async function POST(request: Request): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||||
const payload = intentPayload.safeParse(await readJson(request));
|
const payload = intentPayload.safeParse(await readJson(request));
|
||||||
if (!payload.success) return errorResponse(400, "INVALID_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 {
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
if (error instanceof PrincipalAuthorizationError) {
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
import { immichClient } from "@/modules/immich/client";
|
import { immichClient } from "@/modules/immich/client";
|
||||||
import type { ImmichBinary } from "@/modules/immich/types";
|
import type { ImmichBinary } from "@/modules/immich/types";
|
||||||
import { normalizeUuid } from "@/modules/usages/types";
|
import { normalizeUuid } from "@/modules/usages/types";
|
||||||
@@ -18,6 +19,7 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
|
|||||||
context: DownloadFileRouteContext,
|
context: DownloadFileRouteContext,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
try {
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||||
const downloadId = safeDownloadId((await context.params).downloadId);
|
const downloadId = safeDownloadId((await context.params).downloadId);
|
||||||
if (!downloadId) return genericNotFound();
|
if (!downloadId) return genericNotFound();
|
||||||
@@ -61,6 +63,9 @@ export function createDownloadFileHandler(dependencies: DownloadFileHandlerDepen
|
|||||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
if (error instanceof PrincipalAuthorizationError) {
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -274,6 +274,84 @@ a {
|
|||||||
text-transform: uppercase;
|
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) {
|
@media (max-width: 40rem) {
|
||||||
.form-grid {
|
.form-grid {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
|
|||||||
+6
-1
@@ -2,6 +2,8 @@ import type { Metadata } from "next";
|
|||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
|
import { LegalFooter } from "@/components/layout/legal-footer";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Redaktionsportal | Leon Tonhäuser",
|
title: "Redaktionsportal | Leon Tonhäuser",
|
||||||
description: "Ausgewählte Pressefotos sicher finden und nutzen.",
|
description: "Ausgewählte Pressefotos sicher finden und nutzen.",
|
||||||
@@ -10,7 +12,10 @@ export const metadata: Metadata = {
|
|||||||
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
|
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
return (
|
return (
|
||||||
<html lang="de">
|
<html lang="de">
|
||||||
<body>{children}</body>
|
<body>
|
||||||
|
{children}
|
||||||
|
<LegalFooter />
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { env } from "@/config/env";
|
||||||
|
|
||||||
|
export function LegalFooter() {
|
||||||
|
return (
|
||||||
|
<footer className="legal-footer" aria-label="Rechtliche Hinweise">
|
||||||
|
<a href={env.LEGAL_IMPRINT_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Impressum
|
||||||
|
</a>
|
||||||
|
<a href={env.LEGAL_PRIVACY_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Datenschutz
|
||||||
|
</a>
|
||||||
|
<a href={env.LEGAL_TERMS_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Nutzungs- und Lizenzbedingungen
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,4 +3,5 @@ export * from "./audit";
|
|||||||
export * from "./auth";
|
export * from "./auth";
|
||||||
export * from "./billing";
|
export * from "./billing";
|
||||||
export * from "./editorials";
|
export * from "./editorials";
|
||||||
|
export * from "./rate-limits";
|
||||||
export * from "./usages";
|
export * from "./usages";
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { integer, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fixed-window rate-limit counters. The `key` is a hashed identity (never raw
|
||||||
|
* IP/email — callers hash before calling consumeRateLimit). `windowBoundary` is
|
||||||
|
* an integer epoch-second boundary (Math.floor(now / windowSeconds)) so all
|
||||||
|
* attempts within the same window share a row. The composite primary key makes
|
||||||
|
* the upsert atomic — INSERT … ON CONFLICT DO UPDATE SET count = count + 1.
|
||||||
|
*/
|
||||||
|
export const rateLimits = pgTable(
|
||||||
|
"rate_limits",
|
||||||
|
{
|
||||||
|
key: text("key").notNull(),
|
||||||
|
windowBoundary: integer("window_boundary").notNull(),
|
||||||
|
count: integer("count").notNull().default(1),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [primaryKey({ columns: [table.key, table.windowBoundary] })],
|
||||||
|
);
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { and, desc, eq, gte, lte, sql, type SQL } from "drizzle-orm";
|
||||||
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { auditEvents, users } from "@/db/schema";
|
||||||
|
import type * as schema from "@/db/schema";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type AuditEventRow = {
|
||||||
|
id: string;
|
||||||
|
eventType: string;
|
||||||
|
actorUserId: string | null;
|
||||||
|
actorEmail: string | null;
|
||||||
|
actorType: string;
|
||||||
|
entityType: string;
|
||||||
|
entityId: string;
|
||||||
|
previousValues: unknown;
|
||||||
|
newValues: unknown;
|
||||||
|
occurredAt: Date;
|
||||||
|
requestId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuditFilters = {
|
||||||
|
eventType?: string;
|
||||||
|
dateFrom?: Date;
|
||||||
|
dateTo?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuditPage = {
|
||||||
|
events: AuditEventRow[];
|
||||||
|
nextCursor: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuditQueryRepository = {
|
||||||
|
listEvents(filters: AuditFilters, cursor: string | null, limit: number): Promise<AuditPage>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Repository factory
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAuditQueryRepository(
|
||||||
|
database: NodePgDatabase<typeof schema>,
|
||||||
|
): AuditQueryRepository {
|
||||||
|
return {
|
||||||
|
async listEvents(filters, cursor, limit) {
|
||||||
|
const conditions: SQL[] = [];
|
||||||
|
|
||||||
|
if (filters.eventType) {
|
||||||
|
conditions.push(eq(auditEvents.eventType, filters.eventType));
|
||||||
|
}
|
||||||
|
if (filters.dateFrom) {
|
||||||
|
conditions.push(gte(auditEvents.occurredAt, filters.dateFrom));
|
||||||
|
}
|
||||||
|
if (filters.dateTo) {
|
||||||
|
conditions.push(lte(auditEvents.occurredAt, filters.dateTo));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cursor: base64-encoded "occurredAtIso|id" for stable ordering by
|
||||||
|
// (occurredAt DESC, id DESC). We use a composite cursor because
|
||||||
|
// occurredAt alone is not unique.
|
||||||
|
if (cursor) {
|
||||||
|
const { occurredAtIso, id } = decodeCursor(cursor);
|
||||||
|
conditions.push(
|
||||||
|
// ponytail: row-value comparison via OR — upgrade to tuple > if
|
||||||
|
// Drizzle adds native row-value support for our pg version.
|
||||||
|
// (occurredAt < cursor) OR (occurredAt = cursor AND id < cursorId)
|
||||||
|
sql`(${auditEvents.occurredAt} < ${occurredAtIso} OR (${auditEvents.occurredAt} = ${occurredAtIso} AND ${auditEvents.id} < ${id}))`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await database
|
||||||
|
.select({
|
||||||
|
id: auditEvents.id,
|
||||||
|
eventType: auditEvents.eventType,
|
||||||
|
actorUserId: auditEvents.actorUserId,
|
||||||
|
actorEmail: users.email,
|
||||||
|
actorType: auditEvents.actorType,
|
||||||
|
entityType: auditEvents.entityType,
|
||||||
|
entityId: auditEvents.entityId,
|
||||||
|
previousValues: auditEvents.previousValues,
|
||||||
|
newValues: auditEvents.newValues,
|
||||||
|
occurredAt: auditEvents.occurredAt,
|
||||||
|
requestId: auditEvents.requestId,
|
||||||
|
})
|
||||||
|
.from(auditEvents)
|
||||||
|
.leftJoin(users, eq(auditEvents.actorUserId, users.id))
|
||||||
|
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||||
|
.orderBy(desc(auditEvents.occurredAt), desc(auditEvents.id))
|
||||||
|
.limit(limit + 1);
|
||||||
|
|
||||||
|
const hasMore = rows.length > limit;
|
||||||
|
const pageRows = hasMore ? rows.slice(0, limit) : rows;
|
||||||
|
const nextCursor = hasMore
|
||||||
|
? encodeCursor(pageRows[pageRows.length - 1].occurredAt, pageRows[pageRows.length - 1].id)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
events: pageRows as AuditEventRow[],
|
||||||
|
nextCursor,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeCursor(occurredAt: Date, id: string): string {
|
||||||
|
return Buffer.from(`${occurredAt.toISOString()}|${id}`).toString("base64url");
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeCursor(cursor: string): { occurredAtIso: string; id: string } {
|
||||||
|
const decoded = Buffer.from(cursor, "base64url").toString("utf-8");
|
||||||
|
const [occurredAtIso, id] = decoded.split("|");
|
||||||
|
if (!occurredAtIso || !id) throw new Error("Invalid audit cursor");
|
||||||
|
return { occurredAtIso, id };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Query layer — admin-only via requireAdmin at the route/page layer
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAuditQueryService(repository: AuditQueryRepository) {
|
||||||
|
return {
|
||||||
|
async listAuditEvents(
|
||||||
|
filters: AuditFilters,
|
||||||
|
cursor: string | null,
|
||||||
|
limit = 50,
|
||||||
|
): Promise<AuditPage> {
|
||||||
|
const boundedLimit = Math.min(Math.max(limit, 1), 100);
|
||||||
|
return repository.listEvents(filters, cursor, boundedLimit);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const auditQueryService = createAuditQueryService(createAuditQueryRepository(db));
|
||||||
|
export const listAuditEvents = auditQueryService.listAuditEvents;
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createAuditWriter, type AuditRepository } from "./write";
|
||||||
|
|
||||||
|
function createMockRepo() {
|
||||||
|
const inserted: unknown[] = [];
|
||||||
|
const repository: AuditRepository = {
|
||||||
|
async insert(record) {
|
||||||
|
inserted.push(record);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const spy = vi.spyOn(repository, "insert");
|
||||||
|
return { repository, inserted, spy };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("redacts secrets before writing audit metadata", async () => {
|
||||||
|
const { repository, spy } = createMockRepo();
|
||||||
|
const writer = createAuditWriter(repository);
|
||||||
|
|
||||||
|
await writer.writeAudit({
|
||||||
|
type: "CONFIG_CHECK",
|
||||||
|
entityType: "system",
|
||||||
|
entityId: "config",
|
||||||
|
metadata: { apiKey: "secret", nested: { password: "secret" }, albumId: "a1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
metadata: {
|
||||||
|
apiKey: "[REDACTED]",
|
||||||
|
nested: { password: "[REDACTED]" },
|
||||||
|
albumId: "a1",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("redacts secrets in previousValues and newValues", async () => {
|
||||||
|
const { repository, spy } = createMockRepo();
|
||||||
|
const writer = createAuditWriter(repository);
|
||||||
|
|
||||||
|
await writer.writeAudit({
|
||||||
|
type: "STATUS_CHANGED",
|
||||||
|
entityType: "editorial",
|
||||||
|
entityId: "e1",
|
||||||
|
previousValues: { status: "active", token: "abc" },
|
||||||
|
newValues: { status: "suspended", authorization: "bearer xyz" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
previousValues: { status: "active", token: "[REDACTED]" },
|
||||||
|
newValues: { status: "suspended", authorization: "[REDACTED]" },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("passes through non-secret values unchanged", async () => {
|
||||||
|
const { repository, spy } = createMockRepo();
|
||||||
|
const writer = createAuditWriter(repository);
|
||||||
|
|
||||||
|
await writer.writeAudit({
|
||||||
|
type: "USAGE_CREATED",
|
||||||
|
entityType: "usage",
|
||||||
|
entityId: "u1",
|
||||||
|
metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
metadata: { albumId: "a1", priceCents: 1500, items: [{ id: "x1" }] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("redacts secrets inside arrays", async () => {
|
||||||
|
const { repository, spy } = createMockRepo();
|
||||||
|
const writer = createAuditWriter(repository);
|
||||||
|
|
||||||
|
await writer.writeAudit({
|
||||||
|
type: "BULK",
|
||||||
|
entityType: "system",
|
||||||
|
entityId: "bulk",
|
||||||
|
metadata: { entries: [{ apiKey: "secret", name: "foo" }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
metadata: { entries: [{ apiKey: "[REDACTED]", name: "foo" }] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles null and undefined metadata gracefully", async () => {
|
||||||
|
const { repository, spy } = createMockRepo();
|
||||||
|
const writer = createAuditWriter(repository);
|
||||||
|
|
||||||
|
await writer.writeAudit({
|
||||||
|
type: "SIMPLE",
|
||||||
|
entityType: "system",
|
||||||
|
entityId: "s1",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ metadata: undefined }),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { auditEvents } from "@/db/schema";
|
||||||
|
import type * as schema from "@/db/schema";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type AuditInput = {
|
||||||
|
type: string;
|
||||||
|
actorUserId?: string;
|
||||||
|
actorType?: string;
|
||||||
|
entityType: string;
|
||||||
|
entityId: string;
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
previousValues?: Record<string, unknown>;
|
||||||
|
newValues?: Record<string, unknown>;
|
||||||
|
occurredAt?: Date;
|
||||||
|
requestId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuditRepository = {
|
||||||
|
insert(record: AuditInput): Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Recursive secret redaction
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const SECRET_KEY_PATTERNS = [
|
||||||
|
/key/i,
|
||||||
|
/password/i,
|
||||||
|
/secret/i,
|
||||||
|
/token/i,
|
||||||
|
/auth/i,
|
||||||
|
/credential/i,
|
||||||
|
];
|
||||||
|
|
||||||
|
const REDACTED = "[REDACTED]";
|
||||||
|
|
||||||
|
function isSecretKey(key: string): boolean {
|
||||||
|
return SECRET_KEY_PATTERNS.some((pattern) => pattern.test(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redactSecrets(value: unknown): unknown {
|
||||||
|
if (value === null || value === undefined) return value;
|
||||||
|
if (Array.isArray(value)) return value.map(redactSecrets);
|
||||||
|
if (typeof value === "object") {
|
||||||
|
const result: Record<string, unknown> = {};
|
||||||
|
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
||||||
|
result[key] = isSecretKey(key) ? REDACTED : redactSecrets(child);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Writer factory
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAuditWriter(repository: AuditRepository) {
|
||||||
|
return {
|
||||||
|
async writeAudit(input: AuditInput): Promise<void> {
|
||||||
|
await repository.insert({
|
||||||
|
...input,
|
||||||
|
metadata: redactSecrets(input.metadata) as Record<string, unknown> | undefined,
|
||||||
|
previousValues: redactSecrets(input.previousValues) as Record<string, unknown> | undefined,
|
||||||
|
newValues: redactSecrets(input.newValues) as Record<string, unknown> | undefined,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Drizzle repository — maps the abstract `metadata` field into the schema's
|
||||||
|
// existing jsonb columns. `metadata` is stored in `newValues`; explicit
|
||||||
|
// `previousValues`/`newValues` (state changes) populate both columns.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAuditRepository(
|
||||||
|
database: NodePgDatabase<typeof schema>,
|
||||||
|
): AuditRepository {
|
||||||
|
return {
|
||||||
|
async insert(record) {
|
||||||
|
const hasStateChange = record.previousValues !== undefined || record.newValues !== undefined;
|
||||||
|
const newValues = hasStateChange
|
||||||
|
? (record.newValues ?? null)
|
||||||
|
: (record.metadata ?? null);
|
||||||
|
const previousValues = hasStateChange ? (record.previousValues ?? null) : null;
|
||||||
|
|
||||||
|
await database.insert(auditEvents).values({
|
||||||
|
eventType: record.type,
|
||||||
|
actorUserId: record.actorUserId ?? null,
|
||||||
|
actorType: record.actorType ?? "system",
|
||||||
|
entityType: record.entityType,
|
||||||
|
entityId: record.entityId,
|
||||||
|
previousValues,
|
||||||
|
newValues,
|
||||||
|
occurredAt: record.occurredAt ?? new Date(),
|
||||||
|
requestId: record.requestId ?? null,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Default singleton
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const auditWriter = createAuditWriter(createAuditRepository(db));
|
||||||
|
export const writeAudit = auditWriter.writeAudit;
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
usages,
|
usages,
|
||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import type * as schema from "@/db/schema";
|
import type * as schema from "@/db/schema";
|
||||||
|
import { writeAudit } from "@/modules/audit/write";
|
||||||
import { renderBillingPdf } from "@/modules/pdf/render";
|
import { renderBillingPdf } from "@/modules/pdf/render";
|
||||||
import type { BillingReportSnapshot } from "@/modules/billing/types";
|
import type { BillingReportSnapshot } from "@/modules/billing/types";
|
||||||
|
|
||||||
@@ -304,6 +305,25 @@ export function createReportService({
|
|||||||
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeAudit({
|
||||||
|
type: "billing_report_finalized",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "billing_report",
|
||||||
|
entityId: result.reportId,
|
||||||
|
metadata: {
|
||||||
|
editorialId: input.editorialId,
|
||||||
|
reportNumber: result.reportNumber,
|
||||||
|
invoiceNumber: result.invoiceNumber,
|
||||||
|
netTotalCents,
|
||||||
|
usageCount: selectedUsages.length,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Audit is observability, not a transaction participant.
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
reportId: result.reportId,
|
reportId: result.reportId,
|
||||||
reportNumber: String(result.reportNumber),
|
reportNumber: String(result.reportNumber),
|
||||||
@@ -335,6 +355,19 @@ export function createReportService({
|
|||||||
input.adminUserId,
|
input.adminUserId,
|
||||||
report.usageIds,
|
report.usageIds,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await writeAudit({
|
||||||
|
type: "billing_report_cancelled",
|
||||||
|
actorUserId: input.adminUserId,
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "billing_report",
|
||||||
|
entityId: input.reportId,
|
||||||
|
metadata: { reason, usageCount: report.usageIds.length },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Audit is observability, not a transaction participant.
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import type * as schema from "@/db/schema";
|
import type * as schema from "@/db/schema";
|
||||||
import type { AccountStatus } from "@/modules/auth/principal";
|
import type { AccountStatus } from "@/modules/auth/principal";
|
||||||
|
import { writeAudit } from "@/modules/audit/write";
|
||||||
import { mailer, type Mailer } from "@/modules/mail/mailer";
|
import { mailer, type Mailer } from "@/modules/mail/mailer";
|
||||||
|
|
||||||
export type BillingAddressInput = {
|
export type BillingAddressInput = {
|
||||||
@@ -121,7 +122,22 @@ export function createEditorialService({
|
|||||||
},
|
},
|
||||||
|
|
||||||
async replaceBillingAddress(editorialId: string, input: BillingAddressInput): Promise<string> {
|
async replaceBillingAddress(editorialId: string, input: BillingAddressInput): Promise<string> {
|
||||||
return repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input) });
|
const addressId = await repository.replaceBillingAddress({
|
||||||
|
editorialId,
|
||||||
|
input: validateBillingAddress(input),
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await writeAudit({
|
||||||
|
type: "billing_address_replaced",
|
||||||
|
actorType: "admin",
|
||||||
|
entityType: "editorial_account",
|
||||||
|
entityId: editorialId,
|
||||||
|
metadata: { addressId, countryCode: input.countryCode },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Audit is observability, not a transaction participant.
|
||||||
|
}
|
||||||
|
return addressId;
|
||||||
},
|
},
|
||||||
|
|
||||||
async transitionEditorialStatus(input: {
|
async transitionEditorialStatus(input: {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "./origin";
|
||||||
|
|
||||||
|
function requestWithHeaders({
|
||||||
|
origin,
|
||||||
|
host,
|
||||||
|
}: {
|
||||||
|
origin?: string;
|
||||||
|
host?: string;
|
||||||
|
}): Request {
|
||||||
|
const headers = new Headers();
|
||||||
|
if (origin !== undefined) headers.set("origin", origin);
|
||||||
|
if (host !== undefined) headers.set("host", host);
|
||||||
|
return new Request("https://portal.example.de/api/test", { headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
test("rejects a cross-origin state-changing request", () => {
|
||||||
|
const request = requestWithHeaders({ origin: "https://evil.example", host: "portal.example.de" });
|
||||||
|
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||||
|
expect(() => assertSameOrigin(request)).toThrowError(
|
||||||
|
expect.objectContaining({ code: "CROSS_ORIGIN_REQUEST" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a same-origin request", () => {
|
||||||
|
const request = requestWithHeaders({ origin: "https://portal.example.de", host: "portal.example.de" });
|
||||||
|
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a request with no Origin header (same-page navigation)", () => {
|
||||||
|
const request = requestWithHeaders({ host: "portal.example.de" });
|
||||||
|
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches host only, ignoring scheme", () => {
|
||||||
|
const request = requestWithHeaders({ origin: "http://portal.example.de", host: "portal.example.de" });
|
||||||
|
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches host ignoring path in origin", () => {
|
||||||
|
const request = requestWithHeaders({
|
||||||
|
origin: "https://portal.example.de/some/path",
|
||||||
|
host: "portal.example.de",
|
||||||
|
});
|
||||||
|
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects when host header is missing", () => {
|
||||||
|
const request = requestWithHeaders({ origin: "https://evil.example" });
|
||||||
|
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Same-origin guard for custom state-changing API routes.
|
||||||
|
// Better Auth handles its own route; this guards the portal's custom handlers.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export class CrossOriginRequestError extends Error {
|
||||||
|
readonly name = "CrossOriginRequestError";
|
||||||
|
readonly code = "CROSS_ORIGIN_REQUEST" as const;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super("Cross-origin request rejected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares the request's `Origin` header host against the `Host` header.
|
||||||
|
* Throws `CrossOriginRequestError` on mismatch. A request with no `Origin`
|
||||||
|
* (same-page navigation, same-origin fetch) is allowed — the Origin header is
|
||||||
|
* only sent on cross-origin state-changing requests per the fetch spec.
|
||||||
|
* Only the host is compared (scheme and path are ignored).
|
||||||
|
*/
|
||||||
|
export function assertSameOrigin(request: Request): void {
|
||||||
|
const origin = request.headers.get("origin");
|
||||||
|
if (!origin) return; // Absent Origin = same-origin, allow.
|
||||||
|
|
||||||
|
const host = request.headers.get("host");
|
||||||
|
if (!host) throw new CrossOriginRequestError();
|
||||||
|
|
||||||
|
let originHost: string;
|
||||||
|
try {
|
||||||
|
originHost = new URL(origin).host;
|
||||||
|
} catch {
|
||||||
|
throw new CrossOriginRequestError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (originHost !== host) {
|
||||||
|
throw new CrossOriginRequestError();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { createRateLimiter, loginPolicy, type RateLimitRepository } from "./rate-limit";
|
||||||
|
|
||||||
|
function createMockRepo(): RateLimitRepository & { counts: Map<string, number> } {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
const repository: RateLimitRepository = {
|
||||||
|
async incrementCount(key, _windowBoundary) {
|
||||||
|
const current = (counts.get(key) ?? 0) + 1;
|
||||||
|
counts.set(key, current);
|
||||||
|
return { count: current };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { ...repository, counts };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("blocks the sixth login attempt in a fifteen-minute window", async () => {
|
||||||
|
const repo = createMockRepo();
|
||||||
|
const limiter = createRateLimiter(repo);
|
||||||
|
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(true);
|
||||||
|
}
|
||||||
|
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns retryAfterSeconds when blocked", async () => {
|
||||||
|
const repo = createMockRepo();
|
||||||
|
const limiter = createRateLimiter(repo);
|
||||||
|
|
||||||
|
for (let i = 0; i < 5; i++) await limiter.consume("login:hash", loginPolicy);
|
||||||
|
const result = await limiter.consume("login:hash", loginPolicy);
|
||||||
|
|
||||||
|
expect(result.allowed).toBe(false);
|
||||||
|
expect(result.retryAfterSeconds).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows up to the max attempts", async () => {
|
||||||
|
const repo = createMockRepo();
|
||||||
|
const limiter = createRateLimiter(repo);
|
||||||
|
|
||||||
|
const policy = { maxAttempts: 3, windowSeconds: 60 };
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
expect((await limiter.consume("key:hash", policy)).allowed).toBe(true);
|
||||||
|
}
|
||||||
|
expect((await limiter.consume("key:hash", policy)).allowed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tracks different keys independently", async () => {
|
||||||
|
const repo = createMockRepo();
|
||||||
|
const limiter = createRateLimiter(repo);
|
||||||
|
|
||||||
|
const policy = { maxAttempts: 1, windowSeconds: 60 };
|
||||||
|
expect((await limiter.consume("a:hash", policy)).allowed).toBe(true);
|
||||||
|
expect((await limiter.consume("b:hash", policy)).allowed).toBe(true);
|
||||||
|
expect((await limiter.consume("a:hash", policy)).allowed).toBe(false);
|
||||||
|
expect((await limiter.consume("b:hash", policy)).allowed).toBe(false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { rateLimits } from "@/db/schema";
|
||||||
|
import type * as schema from "@/db/schema";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type RateLimitPolicy = {
|
||||||
|
maxAttempts: number;
|
||||||
|
windowSeconds: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RateLimitResult = {
|
||||||
|
allowed: boolean;
|
||||||
|
retryAfterSeconds: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RateLimitRepository = {
|
||||||
|
incrementCount(key: string, windowBoundary: number): Promise<{ count: number }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Policies — bounded server-side, not configurable via env (Global Constraint)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const loginPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 15 * 60 };
|
||||||
|
export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||||
|
export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||||
|
export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 };
|
||||||
|
export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Limiter factory
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createRateLimiter(repository: RateLimitRepository) {
|
||||||
|
return {
|
||||||
|
async consume(key: string, policy: RateLimitPolicy): Promise<RateLimitResult> {
|
||||||
|
// ponytail: integer-arithmetic fixed window — upgrade to sliding window
|
||||||
|
// if abuse patterns require it. No token-bucket library needed.
|
||||||
|
const nowSeconds = Math.floor(Date.now() / 1000);
|
||||||
|
const windowBoundary = Math.floor(nowSeconds / policy.windowSeconds);
|
||||||
|
|
||||||
|
const { count } = await repository.incrementCount(key, windowBoundary);
|
||||||
|
|
||||||
|
if (count <= policy.maxAttempts) {
|
||||||
|
return { allowed: true, retryAfterSeconds: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const windowEndSeconds = (windowBoundary + 1) * policy.windowSeconds;
|
||||||
|
const retryAfterSeconds = Math.max(1, windowEndSeconds - nowSeconds);
|
||||||
|
return { allowed: false, retryAfterSeconds };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Drizzle repository — atomic upsert via ON CONFLICT
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createRateLimitRepository(
|
||||||
|
database: NodePgDatabase<typeof schema>,
|
||||||
|
): RateLimitRepository {
|
||||||
|
return {
|
||||||
|
async incrementCount(key, windowBoundary) {
|
||||||
|
const result = await database
|
||||||
|
.insert(rateLimits)
|
||||||
|
.values({
|
||||||
|
key,
|
||||||
|
windowBoundary,
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: [rateLimits.key, rateLimits.windowBoundary],
|
||||||
|
set: {
|
||||||
|
count: sql`${rateLimits.count} + 1`,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.returning({ count: rateLimits.count });
|
||||||
|
return { count: result[0].count };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Default singleton
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const rateLimiter = createRateLimiter(createRateLimitRepository(db));
|
||||||
|
export const consumeRateLimit = rateLimiter.consume;
|
||||||
Reference in new issue
Block a user