refactor(admin): gemeinsamer Log-Helfer, eine Rollenprüfung, weniger Doppelcode

- modLog (src/lib/admin/mod-log.ts) ersetzt 43 handgeschriebene
  moderationLog.create-Blöcke in admin, pet-admin, referral-admin,
  curator-admin und lost-report-admin.
- resolveAdminRole ersetzt die dreifache Prüfung ADMIN_OWNER_ID/AdminRole
  (isAdmin, assertAdmin, getMyRole).
- updatePostLogged für hidePost, unhidePost, setAiDisclosure, pinPost,
  unpinPost; deletePostAsModerator für deletePost und deleteReportedPost.

Keine Verhaltensänderung, bestehende Tests unverändert grün.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-06 20:43:56 +02:00
1 parent 42eff68a29
commit 20d6888449
7 files changed
+295 -492

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
import { describe, it, expect, vi } from "vitest";
import { modLog } from "./mod-log";
describe("modLog", () => {
it("ergänzt Moderator, Rolle und IP und setzt einen fehlenden Grund auf null", () => {
const create = vi.fn().mockReturnValue("prisma-promise");
const db = { moderationLog: { create } } as unknown as Parameters<typeof modLog>[0];
const result = modLog(db, { userId: "admin-1", ip: "1.2.3.4" }, "MODERATOR", {
action: "HIDE_POST",
targetType: "POST",
targetId: "post-1",
});
expect(result).toBe("prisma-promise");
expect(create).toHaveBeenCalledWith({
data: {
action: "HIDE_POST",
targetType: "POST",
targetId: "post-1",
reason: null,
moderatorId: "admin-1",
moderatorRole: "MODERATOR",
ipAddress: "1.2.3.4",
},
});
});
});
+36
View File
@@ -0,0 +1,36 @@
import type { Prisma } from "@prisma/client";
/** Wer die Aktion ausgeführt hat — aus dem tRPC-Kontext einer Admin-Prozedur. */
export interface ModLogActor {
userId: string;
ip: string | null;
}
export interface ModLogEntry {
action: string;
targetType: string;
targetId: string;
reason?: string | null;
}
/**
* Ein ModerationLog-Eintrag. Gibt den Prisma-Aufruf zurück (nicht awaited),
* damit er sowohl in `$transaction([...])` als auch in `$transaction(async tx => …)`
* oder einzeln mit `await` passt.
*/
export function modLog(
db: Pick<Prisma.TransactionClient, "moderationLog">,
actor: ModLogActor,
moderatorRole: string,
entry: ModLogEntry
) {
return db.moderationLog.create({
data: {
...entry,
reason: entry.reason ?? null,
moderatorId: actor.userId,
moderatorRole,
ipAddress: actor.ip,
},
});
}
+180 -430
View File
@@ -5,6 +5,7 @@ import { TRPCError } from "@trpc/server";
import { AdminRoleType, BlacklistEntryType, Prisma, type PrismaClient, type ReportReason } from "@prisma/client";
import { clerkClient } from "@clerk/nextjs/server";
import { router, protectedProcedure } from "@/trpc/init";
import { modLog, type ModLogActor } from "@/lib/admin/mod-log";
import { petIdentitySelect } from "@/repositories/pet-repository";
import {
createSignedUploadUrl,
@@ -30,16 +31,16 @@ import { germanNameSelect, withGermanName } from "@/lib/admin/taxonomy-name";
const DATA_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
/** True if userId is the env-bootstrapped super-owner or holds any AdminRole row. */
async function isAdmin(prisma: PrismaClient, userId: string): Promise<boolean> {
if (process.env.ADMIN_OWNER_ID === userId) return true;
const role = await prisma.adminRole.findUnique({ where: { ownerId: userId } });
return role !== null;
}
/** A caller's resolved admin identity for logging — "BOOTSTRAP" has no AdminRole row of its own. */
export type ResolvedAdminRole = AdminRoleType | "BOOTSTRAP";
/** The env-bootstrapped super-owner, the AdminRole row's role, or null for non-admins. */
async function resolveAdminRole(prisma: PrismaClient, userId: string): Promise<ResolvedAdminRole | null> {
if (process.env.ADMIN_OWNER_ID === userId) return "BOOTSTRAP";
const role = await prisma.adminRole.findUnique({ where: { ownerId: userId } });
return role?.role ?? null;
}
const ROLE_RANK: Record<AdminRoleType, number> = {
[AdminRoleType.SUPPORT]: 0,
[AdminRoleType.MODERATOR]: 1,
@@ -57,13 +58,11 @@ export async function assertAdmin(
userId: string,
minRole: AdminRoleType = AdminRoleType.SUPPORT
): Promise<ResolvedAdminRole> {
if (process.env.ADMIN_OWNER_ID === userId) return "BOOTSTRAP";
const role = await prisma.adminRole.findUnique({ where: { ownerId: userId } });
if (!role || ROLE_RANK[role.role] < ROLE_RANK[minRole]) {
const role = await resolveAdminRole(prisma, userId);
if (role === null || (role !== "BOOTSTRAP" && ROLE_RANK[role] < ROLE_RANK[minRole])) {
throw new TRPCError({ code: "FORBIDDEN" });
}
return role.role;
return role;
}
/**
@@ -92,6 +91,70 @@ function rethrowNotFound(err: unknown): never {
throw err;
}
/** Ein Feld eines Beitrags setzen (ausblenden, anpinnen …) und die Aktion im selben Schritt protokollieren. */
async function updatePostLogged(
ctx: { prisma: PrismaClient } & ModLogActor,
callerRole: ResolvedAdminRole,
postId: string,
data: Prisma.PostUpdateInput,
action: string,
reason?: string
): Promise<{ success: true }> {
const post = await ctx.prisma.post.findUnique({ where: { id: postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({ where: { id: postId }, data }),
modLog(ctx.prisma, ctx, callerRole, { action, targetType: "POST", targetId: postId, reason }),
]);
return { success: true };
}
/**
* Beitrag als Moderator löschen: Meldungen, Paw-Backs und repostCount räumt
* postDeleteOps ab (delete-post.ts), Log im selben Schritt. Mit
* `notifyReporters` bekommt jeder Melder danach eine Dankes-Nachricht.
*/
async function deletePostAsModerator(
ctx: { prisma: PrismaClient } & ModLogActor,
callerRole: ResolvedAdminRole,
postId: string,
reason: string | undefined,
notifyReporters: boolean
): Promise<{ success: true }> {
const post = await ctx.prisma.post.findUnique({
where: { id: postId },
select: { repost: { select: { originalPostId: true } }, pet: { select: { name: true } } },
});
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
// Melder vor dem Löschen einsammeln — ihre Meldungen fallen mit dem Beitrag weg.
const reporterPetIds = notifyReporters
? [
...new Set(
(
await ctx.prisma.report.findMany({ where: { targetPostId: postId }, select: { reporterPetId: true } })
).map((r) => r.reporterPetId)
),
]
: [];
await ctx.prisma.$transaction([
...(await postDeleteOps(ctx.prisma, postId, post.repost?.originalPostId)),
modLog(ctx.prisma, ctx, callerRole, { action: "DELETE_POST", targetType: "POST", targetId: postId, reason }),
]);
const message = reportUpheldMessage(describeReportTarget("post", post.pet?.name ?? null));
// Sequential (ensureTeamPet must not race with itself) and
// best-effort: one failing recipient must not stop the others.
for (const petId of reporterPetIds) {
await sendTeamMessage(ctx.prisma, petId, message).catch((err) =>
console.error("[admin] report upheld notification failed", petId, err)
);
}
return { success: true };
}
type Granularity = "day" | "week" | "month";
const BUCKET_COUNT: Record<Granularity, number> = { day: 30, week: 12, month: 12 };
@@ -149,18 +212,14 @@ function countByBucket(timestamps: Date[], buckets: Date[], granularity: Granula
export const adminRouter = router({
/** The caller's own admin identity — no minRole gate, anyone can ask "what am I". */
getMyRole: protectedProcedure.query(async ({ ctx }): Promise<ResolvedAdminRole | null> => {
if (process.env.ADMIN_OWNER_ID === ctx.userId) return "BOOTSTRAP";
const role = await ctx.prisma.adminRole.findUnique({ where: { ownerId: ctx.userId } });
return role?.role ?? null;
}),
getMyRole: protectedProcedure.query(({ ctx }) => resolveAdminRole(ctx.prisma, ctx.userId)),
// ─── Ban status check (no admin role required) ───────────────────────────────
getActiveBan: protectedProcedure
.input(z.object({ ownerId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
// Only the owner themselves or an admin should query ban status
if (input.ownerId !== ctx.userId && !(await isAdmin(ctx.prisma, ctx.userId))) {
if (input.ownerId !== ctx.userId && (await resolveAdminRole(ctx.prisma, ctx.userId)) === null) {
throw new TRPCError({ code: "FORBIDDEN" });
}
const ban = await ctx.prisma.userBan.findUnique({ where: { ownerId: input.ownerId } });
@@ -376,85 +435,21 @@ export const adminRouter = router({
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
// If this post is itself a repost, deleting it must decrement the
// original post's repostCount — the same denormalized counter
// reposts.ts's user-facing delete keeps in sync (see Post model comment).
const post = await ctx.prisma.post.findUnique({
where: { id: input.postId },
select: { repost: { select: { originalPostId: true } } },
});
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
// Meldungen und Paw-Backs anderer Tiere fallen mit weg (delete-post.ts).
await ctx.prisma.$transaction([
...(await postDeleteOps(ctx.prisma, input.postId, post.repost?.originalPostId)),
ctx.prisma.moderationLog.create({
data: {
action: "DELETE_POST",
targetType: "POST",
targetId: input.postId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return deletePostAsModerator(ctx, callerRole, input.postId, input.reason, false);
}),
hidePost: protectedProcedure
.input(z.object({ postId: z.string().min(1), reason: z.string().min(1).max(500) }))
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
const post = await ctx.prisma.post.findUnique({ where: { id: input.postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({
where: { id: input.postId },
data: { hiddenAt: new Date() },
}),
ctx.prisma.moderationLog.create({
data: {
action: "HIDE_POST",
targetType: "POST",
targetId: input.postId,
reason: input.reason,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return updatePostLogged(ctx, callerRole, input.postId, { hiddenAt: new Date() }, "HIDE_POST", input.reason);
}),
unhidePost: protectedProcedure
.input(z.object({ postId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
const post = await ctx.prisma.post.findUnique({ where: { id: input.postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({
where: { id: input.postId },
data: { hiddenAt: null },
}),
ctx.prisma.moderationLog.create({
data: {
action: "UNHIDE_POST",
targetType: "POST",
targetId: input.postId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return updatePostLogged(ctx, callerRole, input.postId, { hiddenAt: null }, "UNHIDE_POST");
}),
// Gitea #18 — legal AI-content disclosure correction. Owners cannot change
@@ -470,27 +465,14 @@ export const adminRouter = router({
)
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
const post = await ctx.prisma.post.findUnique({ where: { id: input.postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({
where: { id: input.postId },
data: { aiDisclosure: input.aiDisclosure },
}),
ctx.prisma.moderationLog.create({
data: {
action: "SET_AI_DISCLOSURE",
targetType: "POST",
targetId: input.postId,
reason: input.reason,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return updatePostLogged(
ctx,
callerRole,
input.postId,
{ aiDisclosure: input.aiDisclosure },
"SET_AI_DISCLOSURE",
input.reason
);
}),
// ─── Blacklist (Gitea #10 Phase 3) ────────────────────────────────────────────
@@ -577,16 +559,11 @@ export const adminRouter = router({
await ctx.prisma
.$transaction(async (tx) => {
const entry = await tx.blacklistEntry.delete({ where: { id: input.id } });
await tx.moderationLog.create({
data: {
action: "DELETE_BLACKLIST_ENTRY",
targetType: "SYSTEM",
targetId: input.id,
reason: `${entry.type.toLowerCase()}: ${entry.value}`,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(tx, ctx, callerRole, {
action: "DELETE_BLACKLIST_ENTRY",
targetType: "SYSTEM",
targetId: input.id,
reason: `${entry.type.toLowerCase()}: ${entry.value}`,
});
})
.catch(rethrowNotFound);
@@ -614,16 +591,11 @@ export const adminRouter = router({
where: { id: deleted.postId },
data: { commentCount: { decrement: 1 } },
});
await tx.moderationLog.create({
data: {
action: "DELETE_COMMENT",
targetType: "COMMENT",
targetId: input.commentId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(tx, ctx, callerRole, {
action: "DELETE_COMMENT",
targetType: "COMMENT",
targetId: input.commentId,
reason: input.reason,
});
});
return { success: true };
@@ -743,16 +715,11 @@ export const adminRouter = router({
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
},
}),
ctx.prisma.moderationLog.create({
data: {
action: "BAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "BAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
}),
]);
return { success: true };
@@ -765,17 +732,7 @@ export const adminRouter = router({
await ctx.prisma
.$transaction([
ctx.prisma.userBan.delete({ where: { ownerId: input.ownerId } }),
ctx.prisma.moderationLog.create({
data: {
action: "UNBAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
modLog(ctx.prisma, ctx, callerRole, { action: "UNBAN_USER", targetType: "USER", targetId: input.ownerId }),
])
.catch(rethrowNotFound);
return { success: true };
@@ -794,16 +751,11 @@ export const adminRouter = router({
create: { ownerId: input.ownerId, reason: input.reason, shadowbannedBy: ctx.userId },
update: { reason: input.reason, shadowbannedBy: ctx.userId, shadowbannedAt: new Date() },
}),
ctx.prisma.moderationLog.create({
data: {
action: "SHADOWBAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "SHADOWBAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
}),
]);
return { success: true };
@@ -816,16 +768,10 @@ export const adminRouter = router({
await ctx.prisma
.$transaction([
ctx.prisma.shadowban.delete({ where: { ownerId: input.ownerId } }),
ctx.prisma.moderationLog.create({
data: {
action: "UNSHADOWBAN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "UNSHADOWBAN_USER",
targetType: "USER",
targetId: input.ownerId,
}),
])
.catch(rethrowNotFound);
@@ -852,16 +798,11 @@ export const adminRouter = router({
ctx.prisma.warning.create({
data: { ownerId: input.ownerId, reason: input.reason, issuedBy: ctx.userId },
}),
ctx.prisma.moderationLog.create({
data: {
action: "WARN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "WARN_USER",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
}),
]);
return warning;
@@ -878,15 +819,10 @@ export const adminRouter = router({
where: { id: input.petId },
data: { isVerified: input.isVerified },
}),
ctx.prisma.moderationLog.create({
data: {
action: input.isVerified ? "VERIFY_PET" : "UNVERIFY_PET",
targetType: "PET",
targetId: input.petId,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: input.isVerified ? "VERIFY_PET" : "UNVERIFY_PET",
targetType: "PET",
targetId: input.petId,
}),
]);
return pet;
@@ -1005,16 +941,11 @@ export const adminRouter = router({
...(allMet
? [ctx.prisma.pet.update({ where: { id: request.petId }, data: { isVerified: true } })]
: []),
ctx.prisma.moderationLog.create({
data: {
action: allMet ? "APPROVE_VERIFICATION_REQUEST" : "REJECT_VERIFICATION_REQUEST",
targetType: "PET",
targetId: request.petId,
reason: reviewNote,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: allMet ? "APPROVE_VERIFICATION_REQUEST" : "REJECT_VERIFICATION_REQUEST",
targetType: "PET",
targetId: request.petId,
reason: reviewNote,
}),
]);
@@ -1053,15 +984,10 @@ export const adminRouter = router({
// Written after deletion succeeds — targetId/moderatorId have no FK to
// Owner, so the now-deleted account doesn't block this insert.
await ctx.prisma.moderationLog.create({
data: {
action: "DELETE_ACCOUNT",
targetType: "USER",
targetId: input.ownerId,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(ctx.prisma, ctx, callerRole, {
action: "DELETE_ACCOUNT",
targetType: "USER",
targetId: input.ownerId,
});
return { success: true };
@@ -1234,17 +1160,7 @@ export const adminRouter = router({
}),
});
await ctx.prisma.moderationLog.create({
data: {
action: "DATA_EXPORT",
targetType: "USER",
targetId: input.ownerId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
});
await modLog(ctx.prisma, ctx, callerRole, { action: "DATA_EXPORT", targetType: "USER", targetId: input.ownerId });
return { success: true, sentTo: email };
}),
@@ -1360,16 +1276,11 @@ export const adminRouter = router({
if (!report) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.report.delete({ where: { id: input.reportId } }),
ctx.prisma.moderationLog.create({
data: {
action: "DISMISS_REPORT",
targetType: "REPORT",
targetId: input.reportId,
reason: input.message?.trim() || null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "DISMISS_REPORT",
targetType: "REPORT",
targetId: input.reportId,
reason: input.message?.trim() || null,
}),
]);
@@ -1409,49 +1320,7 @@ export const adminRouter = router({
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
// Same repostCount fix as deletePost above.
const post = await ctx.prisma.post.findUnique({
where: { id: input.postId },
select: { repost: { select: { originalPostId: true } }, pet: { select: { name: true } } },
});
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
// Report.targetPostId is a plain string, not a relation — deleting the
// post does NOT cascade to its reports, they'd linger in the queue
// pointing at nothing. Collect the reporters first, delete the reports
// in the same transaction.
const reports = await ctx.prisma.report.findMany({
where: { targetPostId: input.postId },
select: { reporterPetId: true },
});
// Comments and reactions cascade via the Prisma schema; reports and paw-backs don't (delete-post.ts).
await ctx.prisma.$transaction([
...(await postDeleteOps(ctx.prisma, input.postId, post.repost?.originalPostId)),
ctx.prisma.moderationLog.create({
data: {
action: "DELETE_POST",
targetType: "POST",
targetId: input.postId,
reason: input.reason ?? null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
if (input.notifyReporters) {
const message = reportUpheldMessage(describeReportTarget("post", post.pet?.name ?? null));
const reporterPetIds = [...new Set(reports.map((r) => r.reporterPetId))];
// Sequential (ensureTeamPet must not race with itself) and
// best-effort: one failing recipient must not stop the others.
for (const petId of reporterPetIds) {
await sendTeamMessage(ctx.prisma, petId, message).catch((err) =>
console.error("[admin] report upheld notification failed", petId, err)
);
}
}
return { success: true };
return deletePostAsModerator(ctx, callerRole, input.postId, input.reason, input.notifyReporters);
}),
// ─── Ad media upload ─────────────────────────────────────────────────────────
@@ -1510,16 +1379,11 @@ export const adminRouter = router({
createdBy: ctx.userId,
},
});
await tx.moderationLog.create({
data: {
action: "CREATE_AD",
targetType: "AD",
targetId: ad.id,
reason: input.title,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(tx, ctx, callerRole, {
action: "CREATE_AD",
targetType: "AD",
targetId: ad.id,
reason: input.title,
});
return ad;
});
@@ -1553,16 +1417,7 @@ export const adminRouter = router({
endDate: endDate ? new Date(endDate) : endDate === null ? null : undefined,
},
}),
ctx.prisma.moderationLog.create({
data: {
action: "UPDATE_AD",
targetType: "AD",
targetId: id,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
modLog(ctx.prisma, ctx, callerRole, { action: "UPDATE_AD", targetType: "AD", targetId: id }),
]);
return ad;
}),
@@ -1573,16 +1428,7 @@ export const adminRouter = router({
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
await ctx.prisma.$transaction([
ctx.prisma.advertisement.delete({ where: { id: input.id } }),
ctx.prisma.moderationLog.create({
data: {
action: "DELETE_AD",
targetType: "AD",
targetId: input.id,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
modLog(ctx.prisma, ctx, callerRole, { action: "DELETE_AD", targetType: "AD", targetId: input.id }),
]);
return { success: true };
}),
@@ -1663,16 +1509,11 @@ export const adminRouter = router({
const track = await tx.musicTrack.create({
data: { ...input, createdBy: ctx.userId },
});
await tx.moderationLog.create({
data: {
action: "CREATE_MUSIC_TRACK",
targetType: "MUSIC_TRACK",
targetId: track.id,
reason: input.title,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(tx, ctx, callerRole, {
action: "CREATE_MUSIC_TRACK",
targetType: "MUSIC_TRACK",
targetId: track.id,
reason: input.title,
});
return track;
});
@@ -1693,16 +1534,7 @@ export const adminRouter = router({
const { id, ...rest } = input;
const [track] = await ctx.prisma.$transaction([
ctx.prisma.musicTrack.update({ where: { id }, data: rest }),
ctx.prisma.moderationLog.create({
data: {
action: "UPDATE_MUSIC_TRACK",
targetType: "MUSIC_TRACK",
targetId: id,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
modLog(ctx.prisma, ctx, callerRole, { action: "UPDATE_MUSIC_TRACK", targetType: "MUSIC_TRACK", targetId: id }),
]);
return track;
}),
@@ -1717,15 +1549,10 @@ export const adminRouter = router({
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
await ctx.prisma.$transaction([
ctx.prisma.musicTrack.delete({ where: { id: input.id } }),
ctx.prisma.moderationLog.create({
data: {
action: "DELETE_MUSIC_TRACK",
targetType: "MUSIC_TRACK",
targetId: input.id,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "DELETE_MUSIC_TRACK",
targetType: "MUSIC_TRACK",
targetId: input.id,
}),
]);
return { success: true };
@@ -1778,16 +1605,11 @@ export const adminRouter = router({
create: { ownerId: input.ownerId, role: input.role, grantedBy: ctx.userId },
update: { role: input.role, grantedBy: ctx.userId, grantedAt: new Date() },
}),
ctx.prisma.moderationLog.create({
data: {
action: "GRANT_ROLE",
targetType: "USER",
targetId: input.ownerId,
reason: input.role,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "GRANT_ROLE",
targetType: "USER",
targetId: input.ownerId,
reason: input.role,
}),
]);
return role;
@@ -1800,16 +1622,7 @@ export const adminRouter = router({
await ctx.prisma
.$transaction([
ctx.prisma.adminRole.delete({ where: { ownerId: input.ownerId } }),
ctx.prisma.moderationLog.create({
data: {
action: "REVOKE_ROLE",
targetType: "USER",
targetId: input.ownerId,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
modLog(ctx.prisma, ctx, callerRole, { action: "REVOKE_ROLE", targetType: "USER", targetId: input.ownerId }),
])
.catch(rethrowNotFound);
return { success: true };
@@ -1841,16 +1654,10 @@ export const adminRouter = router({
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
await setMaintenanceMode(input.enabled);
await ctx.prisma.moderationLog.create({
data: {
action: input.enabled ? "ENABLE_MAINTENANCE_MODE" : "DISABLE_MAINTENANCE_MODE",
targetType: "SYSTEM",
targetId: "maintenance",
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(ctx.prisma, ctx, callerRole, {
action: input.enabled ? "ENABLE_MAINTENANCE_MODE" : "DISABLE_MAINTENANCE_MODE",
targetType: "SYSTEM",
targetId: "maintenance",
});
return { success: true };
}),
@@ -1866,16 +1673,10 @@ export const adminRouter = router({
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
await setStoryEditorEnabled(input.enabled);
await ctx.prisma.moderationLog.create({
data: {
action: input.enabled ? "ENABLE_STORY_EDITOR" : "DISABLE_STORY_EDITOR",
targetType: "SYSTEM",
targetId: "story-editor",
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(ctx.prisma, ctx, callerRole, {
action: input.enabled ? "ENABLE_STORY_EDITOR" : "DISABLE_STORY_EDITOR",
targetType: "SYSTEM",
targetId: "story-editor",
});
return { success: true };
}),
@@ -1884,54 +1685,14 @@ export const adminRouter = router({
.input(z.object({ postId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
const post = await ctx.prisma.post.findUnique({ where: { id: input.postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({
where: { id: input.postId },
data: { pinnedAt: new Date() },
}),
ctx.prisma.moderationLog.create({
data: {
action: "PIN_POST",
targetType: "POST",
targetId: input.postId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return updatePostLogged(ctx, callerRole, input.postId, { pinnedAt: new Date() }, "PIN_POST");
}),
unpinPost: protectedProcedure
.input(z.object({ postId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
const post = await ctx.prisma.post.findUnique({ where: { id: input.postId } });
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
await ctx.prisma.$transaction([
ctx.prisma.post.update({
where: { id: input.postId },
data: { pinnedAt: null },
}),
ctx.prisma.moderationLog.create({
data: {
action: "UNPIN_POST",
targetType: "POST",
targetId: input.postId,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
}),
]);
return { success: true };
return updatePostLogged(ctx, callerRole, input.postId, { pinnedAt: null }, "UNPIN_POST");
}),
// ─── Broadcast / System-Mitteilungen (Gitea #10, Phase 1) ────────────────
@@ -1947,16 +1708,10 @@ export const adminRouter = router({
const broadcast = await ctx.prisma.broadcast.create({
data: { title: input.title.trim(), body: input.body.trim(), createdBy: ctx.userId },
});
await ctx.prisma.moderationLog.create({
data: {
action: "SEND_BROADCAST",
targetType: "SYSTEM",
targetId: broadcast.id,
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(ctx.prisma, ctx, callerRole, {
action: "SEND_BROADCAST",
targetType: "SYSTEM",
targetId: broadcast.id,
});
return broadcast;
}),
@@ -1974,16 +1729,11 @@ export const adminRouter = router({
await ctx.prisma.$transaction([
// BroadcastReceipt rows cascade (schema.prisma: onDelete: Cascade).
ctx.prisma.broadcast.delete({ where: { id: input.broadcastId } }),
ctx.prisma.moderationLog.create({
data: {
action: "DELETE_BROADCAST",
targetType: "SYSTEM",
targetId: input.broadcastId,
reason: input.reason,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "DELETE_BROADCAST",
targetType: "SYSTEM",
targetId: input.broadcastId,
reason: input.reason,
}),
]);
return { success: true };
+6 -10
View File
@@ -2,6 +2,7 @@ import "server-only";
import { z } from "zod";
import { AdminRoleType } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import { modLog } from "@/lib/admin/mod-log";
import { assertAdmin } from "@/trpc/routers/admin";
import {
DEFAULT_WELCOME_TEXT_DE,
@@ -56,16 +57,11 @@ export const curatorAdminRouter = router({
create: { id: 1, ...input, updatedBy: ctx.userId },
update: { ...input, updatedBy: ctx.userId },
}),
ctx.prisma.moderationLog.create({
data: {
action: "UPDATE_CURATOR_SETTINGS",
targetType: "SYSTEM",
targetId: "curator-settings",
reason: `welcome=${input.welcomeEnabled} follow=${input.autoFollowEnabled}`,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: "UPDATE_CURATOR_SETTINGS",
targetType: "SYSTEM",
targetId: "curator-settings",
reason: `welcome=${input.welcomeEnabled} follow=${input.autoFollowEnabled}`,
}),
]);
return settings;
+6 -10
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { AdminRoleType, type Prisma } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import { modLog } from "@/lib/admin/mod-log";
import { assertAdmin } from "@/trpc/routers/admin";
const PAGE_SIZE = 50;
@@ -80,16 +81,11 @@ export const lostReportAdminRouter = router({
: ctx.prisma.lostReport.update({ where: { id: report.id }, data: { foundAt: report.foundAt ?? new Date(), contactPhone: null, contactEmail: null } }),
// Abzeichen nur entfernen, wenn es diese Meldung war (aktive Meldung).
...(report.foundAt ? [] : [ctx.prisma.pet.update({ where: { id: report.petId }, data: { lostSince: null } })]),
ctx.prisma.moderationLog.create({
data: {
action: input.mode === "DELETE" ? "DELETE_LOST_REPORT" : "CLOSE_LOST_REPORT",
targetType: "PET",
targetId: report.petId,
reason: input.reason || null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
modLog(ctx.prisma, ctx, callerRole, {
action: input.mode === "DELETE" ? "DELETE_LOST_REPORT" : "CLOSE_LOST_REPORT",
targetType: "PET",
targetId: report.petId,
reason: input.reason || null,
}),
]);
return { success: true };
+7 -19
View File
@@ -4,6 +4,7 @@ import { TRPCError } from "@trpc/server";
import { AdminRoleType, type Prisma } from "@prisma/client";
import { clerkClient } from "@clerk/nextjs/server";
import { router, protectedProcedure } from "@/trpc/init";
import { modLog } from "@/lib/admin/mod-log";
import { assertAdmin } from "@/trpc/routers/admin";
import { deletePetCompletely } from "@/lib/delete-pet";
import { deleteFiles } from "@/lib/supabase-storage";
@@ -28,13 +29,6 @@ function escapeHtml(text: string): string {
return text.replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch] ?? ch);
}
async function log(
prisma: Prisma.TransactionClient | Parameters<typeof deletePetCompletely>[0],
data: { action: string; targetId: string; reason: string | null; moderatorId: string; moderatorRole: string; ipAddress: string | null }
) {
await prisma.moderationLog.create({ data: { ...data, targetType: "PET" } });
}
export const petAdminRouter = router({
list: protectedProcedure
.input(
@@ -235,13 +229,11 @@ export const petAdminRouter = router({
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
await ctx.prisma.pet.update({ where: { id: input.petId }, data: { isFoundingMember: input.value } });
await log(ctx.prisma, {
await modLog(ctx.prisma, ctx, callerRole, {
action: "SET_FOUNDING_MEMBER",
targetType: "PET",
targetId: input.petId,
reason: String(input.value),
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
});
return { success: true };
}),
@@ -274,13 +266,11 @@ export const petAdminRouter = router({
if (fields.has("avatar") && pet.avatarKey) {
await deleteFiles([pet.avatarKey]).catch((err) => console.error("[pet-admin] avatar delete failed", err));
}
await log(ctx.prisma, {
await modLog(ctx.prisma, ctx, callerRole, {
action: "CLEAR_PET_CONTENT",
targetType: "PET",
targetId: input.petId,
reason: `${input.fields.join(", ")}: ${input.reason}`,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
});
if (input.notifyOwner) {
await sendTeamMessage(
@@ -315,13 +305,11 @@ export const petAdminRouter = router({
}
await deletePetCompletely(ctx.prisma, input.petId);
await log(ctx.prisma, {
await modLog(ctx.prisma, ctx, callerRole, {
action: "DELETE_PET",
targetType: "PET",
targetId: input.petId,
reason: `${pet.name}: ${input.reason}`,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
});
if (!input.notifyOwner) return { notified: "none" };
+32 -23
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { AdminRoleType, Prisma } from "@prisma/client";
import { router, protectedProcedure } from "@/trpc/init";
import { modLog } from "@/lib/admin/mod-log";
import { assertAdmin } from "@/trpc/routers/admin";
import { creditInviter, rebuildOwnerRankCache, recomputeReferralRanks } from "@/lib/referrals";
import { notify } from "@/lib/notify";
@@ -65,8 +66,11 @@ export const referralAdminRouter = router({
.$transaction(async (tx) => {
const rank = await tx.referralRank.create({ data: input });
await recomputeReferralRanks(tx);
await tx.moderationLog.create({
data: { action: "CREATE_REFERRAL_RANK", targetType: "SYSTEM", targetId: rank.id, reason: `${input.key} ab ${input.threshold}`, moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
await modLog(tx, ctx, callerRole, {
action: "CREATE_REFERRAL_RANK",
targetType: "SYSTEM",
targetId: rank.id,
reason: `${input.key} ab ${input.threshold}`,
});
return rank;
})
@@ -83,8 +87,11 @@ export const referralAdminRouter = router({
const rank = await tx.referralRank.update({ where: { id }, data });
await recomputeReferralRanks(tx);
const action = data.isActive === false ? "DEACTIVATE_REFERRAL_RANK" : "UPDATE_REFERRAL_RANK";
await tx.moderationLog.create({
data: { action, targetType: "SYSTEM", targetId: id, reason: `${rank.key}: ${Object.keys(data).join(", ")}`, moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
await modLog(tx, ctx, callerRole, {
action,
targetType: "SYSTEM",
targetId: id,
reason: `${rank.key}: ${Object.keys(data).join(", ")}`,
});
return rank;
})
@@ -113,8 +120,11 @@ export const referralAdminRouter = router({
create: { id: 1, ...input, updatedBy: ctx.userId },
update: { ...input, updatedBy: ctx.userId },
}),
ctx.prisma.moderationLog.create({
data: { action: "UPDATE_REFERRAL_SETTINGS", targetType: "SYSTEM", targetId: "referral-settings", reason: JSON.stringify(input), moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
modLog(ctx.prisma, ctx, callerRole, {
action: "UPDATE_REFERRAL_SETTINGS",
targetType: "SYSTEM",
targetId: "referral-settings",
reason: JSON.stringify(input),
}),
]);
return settings;
@@ -219,9 +229,7 @@ export const referralAdminRouter = router({
if (claimed.count === 0) throw new TRPCError({ code: "NOT_FOUND" });
const invitee = await tx.owner.findUnique({ where: { id: input.ownerId }, select: { invitedById: true } });
if (invitee?.invitedById) await creditInviter(tx, invitee.invitedById);
await tx.moderationLog.create({
data: { action: "APPROVE_REFERRAL", targetType: "USER", targetId: input.ownerId, reason: null, moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
});
await modLog(tx, ctx, callerRole, { action: "APPROVE_REFERRAL", targetType: "USER", targetId: input.ownerId });
});
return { success: true };
}),
@@ -244,8 +252,11 @@ export const referralAdminRouter = router({
data: { qualifiedReferralCount: { decrement: 1 } },
});
}
await tx.moderationLog.create({
data: { action: "REVOKE_REFERRAL", targetType: "USER", targetId: input.ownerId, reason: input.reason, moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
await modLog(tx, ctx, callerRole, {
action: "REVOKE_REFERRAL",
targetType: "USER",
targetId: input.ownerId,
reason: input.reason,
});
});
return { success: true };
@@ -267,8 +278,11 @@ export const referralAdminRouter = router({
update: { revokedAt: new Date(), revokedBy: ctx.userId, revokeReason: input.reason },
});
await rebuildOwnerRankCache(tx, input.ownerId);
await tx.moderationLog.create({
data: { action: "REVOKE_REFERRAL_RANK", targetType: "USER", targetId: input.ownerId, reason: `${input.rankId}: ${input.reason}`, moderatorId: ctx.userId, moderatorRole: callerRole, ipAddress: ctx.ip },
await modLog(tx, ctx, callerRole, {
action: "REVOKE_REFERRAL_RANK",
targetType: "USER",
targetId: input.ownerId,
reason: `${input.rankId}: ${input.reason}`,
});
});
return { success: true };
@@ -293,16 +307,11 @@ export const referralAdminRouter = router({
update: { revokedAt: null, revokedBy: null, revokeReason: null },
});
await rebuildOwnerRankCache(tx, input.ownerId);
await tx.moderationLog.create({
data: {
action: existing?.revokedAt ? "RESTORE_REFERRAL_RANK" : "GRANT_REFERRAL_RANK",
targetType: "USER",
targetId: input.ownerId,
reason: `${input.rankId}${input.note ? `: ${input.note}` : ""}`,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
await modLog(tx, ctx, callerRole, {
action: existing?.revokedAt ? "RESTORE_REFERRAL_RANK" : "GRANT_REFERRAL_RANK",
targetType: "USER",
targetId: input.ownerId,
reason: `${input.rankId}${input.note ? `: ${input.note}` : ""}`,
});
return !!existing?.revokedAt;
});