feat: jwt cache, redis health, help-ticket admin, and write rate limits
Deploy / release (push) Skipped
Deploy / deploy (push) Successful in 1m33s

Cut Auth.js DB load with cached jwtVersion checks, surface Redis in /api/health and deploy warnings, add admin help-center ticket reply UI, rate-limit API tickets/reactions/referral claims, and revoke PATs on sign-out-everywhere.

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-07-21 21:58:48 +02:00
1 parent 3bb96eb6f3
commit 968ca15c27
23 files changed
+1344 -205

No files matched your search

@@ -0,0 +1,288 @@
"use client";
import { ArrowLeft, Loader2, Mail, Send, Shield, User } from "lucide-react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import {
closeHelpCenterTicket,
reopenHelpCenterTicket,
replyHelpCenterTicket,
} from "@/actions/admin-help-tickets";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { useServerAction } from "@/hooks/use-server-action";
interface ThreadMessage {
key: string;
userId: number;
username: string;
isStaff: boolean;
content: string;
createdAt: string;
}
interface HelpTicketInfo {
id: string;
title: string;
open: boolean;
createdAt: string;
updatedAt: string;
creator: {
id: number;
username: string;
rank: number;
mail: string;
} | null;
}
export function AdminHelpTicketDetail({
ticket,
messages: initialMessages,
canEdit,
}: {
ticket: HelpTicketInfo;
messages: ThreadMessage[];
canEdit: boolean;
}) {
const t = useTranslations("pages.admin.helpTickets");
const [messages, setMessages] = useState(initialMessages);
const [reply, setReply] = useState("");
const { run, isPending } = useServerAction();
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setMessages(initialMessages);
}, [initialMessages]);
// biome-ignore lint/correctness/useExhaustiveDependencies: scroll when thread updates
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
function handleReply() {
if (!reply.trim() || isPending) return;
run(
() =>
replyHelpCenterTicket({
ticketId: ticket.id,
content: reply.trim(),
}),
{
successMessage: t("success.replied"),
onSuccess: () => setReply(""),
},
);
}
function handleClose() {
run(
() => closeHelpCenterTicket({ ticketId: ticket.id }),
{ successMessage: t("success.closed") },
);
}
function handleReopen() {
run(
() => reopenHelpCenterTicket({ ticketId: ticket.id }),
{ successMessage: t("success.reopened") },
);
}
return (
<div className="space-y-6">
<div className="flex items-start gap-4">
<Link href="/admin/help-tickets">
<Button variant="ghost" size="icon" aria-label={t("backToList")}>
<ArrowLeft className="h-4 w-4" />
</Button>
</Link>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm text-muted-foreground font-mono">
#{ticket.id}
</span>
<Badge variant={ticket.open ? "default" : "secondary"}>
{ticket.open ? t("statusOpen") : t("statusClosed")}
</Badge>
</div>
<h1 className="text-2xl font-bold">{ticket.title}</h1>
</div>
</div>
<div className="grid gap-6 lg:grid-cols-[1fr_300px]">
<div className="space-y-4">
<Card className="overflow-hidden">
<CardHeader className="pb-2 border-b">
<CardTitle className="text-sm">{t("threadTitle")}</CardTitle>
</CardHeader>
<div className="max-h-[600px] overflow-y-auto p-4 space-y-4">
{messages.map((msg) => (
<div key={msg.key} className="flex gap-3">
<div className="shrink-0">
<div className="w-9 h-9 rounded-full bg-accent flex items-center justify-center text-xs font-bold">
{msg.isStaff ? (
<Shield className="h-4 w-4 text-primary" />
) : (
<User className="h-4 w-4" />
)}
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span
className={`text-xs font-semibold ${msg.isStaff ? "text-primary" : ""}`}
>
{msg.username}
{msg.isStaff ? ` (${t("staffBadge")})` : ""}
</span>
<span className="text-[10px] text-muted-foreground">
{new Date(msg.createdAt).toLocaleString()}
</span>
</div>
<div
className={`rounded-lg px-4 py-2.5 text-sm leading-relaxed ${
msg.isStaff
? "bg-primary/10 border border-primary/20"
: "bg-muted"
}`}
>
<p className="whitespace-pre-wrap break-words">
{msg.content}
</p>
</div>
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
{canEdit && ticket.open && (
<div className="border-t p-4">
<div className="flex gap-2">
<Textarea
value={reply}
onChange={(e) => setReply(e.target.value)}
placeholder={t("replyPlaceholder")}
rows={3}
maxLength={5000}
className="resize-none"
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleReply();
}
}}
/>
<Button
onClick={handleReply}
disabled={isPending || !reply.trim()}
size="icon"
className="shrink-0 h-auto"
aria-label={t("replySubmit")}
>
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
</Button>
</div>
<p className="text-[10px] text-muted-foreground mt-1">
{t("replyHint")}
</p>
</div>
)}
{!ticket.open && (
<div className="border-t p-4 text-center text-sm text-muted-foreground">
{t("closedHint")}
</div>
)}
</Card>
</div>
<div className="space-y-4">
{canEdit && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">{t("actionsTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{ticket.open ? (
<Button
variant="outline"
size="sm"
className="w-full"
disabled={isPending}
onClick={handleClose}
>
{t("closeSubmit")}
</Button>
) : (
<Button
variant="outline"
size="sm"
className="w-full"
disabled={isPending}
onClick={handleReopen}
>
{t("reopenSubmit")}
</Button>
)}
</CardContent>
</Card>
)}
{ticket.creator && (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">{t("requesterTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
<Link
href={`/admin/users/show/${ticket.creator.id}`}
className="flex items-center gap-2 text-sm font-medium hover:text-primary"
>
<User className="h-3.5 w-3.5" />
{ticket.creator.username}
<Badge variant="outline" className="text-[10px]">
{t("rankLabel", { rank: ticket.creator.rank })}
</Badge>
</Link>
{ticket.creator.mail ? (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Mail className="h-3 w-3" />
{ticket.creator.mail}
</div>
) : null}
</CardContent>
</Card>
)}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">{t("detailsTitle")}</CardTitle>
</CardHeader>
<CardContent className="space-y-2 text-xs text-muted-foreground">
<div className="flex justify-between gap-2">
<span>{t("colCreated")}</span>
<span>{new Date(ticket.createdAt).toLocaleString()}</span>
</div>
<div className="flex justify-between gap-2">
<span>{t("colUpdated")}</span>
<span>{new Date(ticket.updatedAt).toLocaleString()}</span>
</div>
<div className="flex justify-between gap-2">
<span>{t("messageCountLabel")}</span>
<span>{messages.length}</span>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { notFound, redirect } from "next/navigation";
import { positiveBigInt } from "@/lib/api";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { AdminHelpTicketDetail } from "./admin-help-ticket-detail";
export const dynamic = "force-dynamic";
const STAFF_RANK_THRESHOLD = 4;
export default async function AdminHelpTicketDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { session, permissions } = await getAdminContext();
if (!canAccess(permissions, PERMS.TICKETS_VIEW, session.user.rank)) {
redirect("/admin");
}
const { id } = await params;
const ticketId = positiveBigInt(id);
if (!ticketId) notFound();
const ticket = await prisma.websiteHelpCenterTickets.findUnique({
where: { id: ticketId },
select: {
id: true,
userId: true,
title: true,
content: true,
open: true,
createdAt: true,
updatedAt: true,
},
});
if (!ticket) notFound();
const replies = await prisma.websiteHelpCenterTicketReplies.findMany({
where: { ticketId: ticket.id },
orderBy: { id: "asc" },
select: {
id: true,
userId: true,
content: true,
createdAt: true,
},
});
const authorIds = [
...new Set([
...(ticket.userId != null ? [ticket.userId] : []),
...replies.map((r) => r.userId),
]),
];
const users =
authorIds.length > 0
? await prisma.user.findMany({
where: { id: { in: authorIds } },
select: {
id: true,
username: true,
rank: true,
mail: true,
},
})
: [];
const userById = new Map(users.map((u) => [u.id, u]));
const openerId = ticket.userId;
const messages = [
{
key: "opening",
userId: openerId ?? 0,
username:
openerId != null
? (userById.get(openerId)?.username ?? `#${openerId}`)
: "—",
isStaff: false,
content: ticket.content,
createdAt: (ticket.createdAt ?? new Date()).toISOString(),
},
...replies.map((r) => {
const user = userById.get(r.userId);
const isStaff =
r.userId !== openerId && (user?.rank ?? 0) >= STAFF_RANK_THRESHOLD;
return {
key: String(r.id),
userId: r.userId,
username: user?.username ?? `#${r.userId}`,
isStaff,
content: r.content,
createdAt: (r.createdAt ?? new Date()).toISOString(),
};
}),
];
const creator =
openerId != null ? userById.get(openerId) : undefined;
const canEdit = canAccess(permissions, PERMS.TICKETS_EDIT, session.user.rank);
return (
<AdminHelpTicketDetail
ticket={{
id: String(ticket.id),
title: ticket.title,
open: ticket.open,
createdAt: (ticket.createdAt ?? new Date()).toISOString(),
updatedAt: (ticket.updatedAt ?? new Date()).toISOString(),
creator: creator
? {
id: creator.id,
username: creator.username,
rank: creator.rank,
mail: creator.mail ?? "",
}
: null,
}}
messages={messages}
canEdit={canEdit}
/>
);
}
@@ -0,0 +1,89 @@
"use client";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { DataTable } from "@/components/admin/data-table";
import { Badge } from "@/components/ui/badge";
import type { DataTableColumn, PaginatedResult } from "@/types";
export interface HelpTicketRow {
id: string;
title: string;
user: string;
userId: number | null;
replies: number;
open: boolean;
date: string;
updated: string;
}
export function HelpTicketsTable({
data,
}: {
data: PaginatedResult<HelpTicketRow>;
}) {
const t = useTranslations("pages.admin.helpTickets");
const columns: DataTableColumn<HelpTicketRow>[] = [
{
key: "title",
label: t("colTicket"),
sortable: true,
render: (_value, row) => (
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground font-mono">
#{row.id}
</span>
<Link
href={`/admin/help-tickets/${row.id}`}
className="font-medium truncate hover:underline"
>
{row.title}
</Link>
</div>
<div className="text-xs text-muted-foreground">
{t("meta", { user: row.user, count: row.replies })}
</div>
</div>
),
},
{
key: "open",
label: t("colStatus"),
sortable: true,
filterKey: "filter_status",
filterOptions: [
{ label: t("presetOpen"), value: "open" },
{ label: t("statusClosed"), value: "closed" },
],
render: (value) => {
const open = value === true || value === "true";
return (
<Badge
variant={open ? "default" : "secondary"}
className="text-[0.7rem]"
>
{open ? t("statusOpen") : t("statusClosed")}
</Badge>
);
},
},
{ key: "user", label: t("colUser"), sortable: true },
{ key: "date", label: t("colCreated"), sortable: true },
{ key: "updated", label: t("colUpdated"), sortable: true },
];
return (
<DataTable
data={data}
columns={columns}
searchPlaceholder={t("searchPlaceholder")}
presets={[
{ label: t("presetOpen"), params: { filter_status: "open" } },
{ label: t("statusClosed"), params: { filter_status: "closed" } },
{ label: t("presetAll"), params: { filter_status: "all" } },
]}
/>
);
}
+187
View File
@@ -0,0 +1,187 @@
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import type { Prisma } from "@/generated/prisma/client";
import { StatusCard } from "@/components/admin/dashboard";
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import {
HelpTicketsTable,
type HelpTicketRow,
} from "./help-tickets-table";
export const dynamic = "force-dynamic";
function fromDate(d: Date | null | undefined): string {
return d ? d.toISOString().slice(0, 10) : "—";
}
export default async function AdminHelpTicketsPage({
searchParams,
}: {
searchParams: Promise<Record<string, string>>;
}) {
const { session, permissions } = await getAdminContext();
if (!canAccess(permissions, PERMS.TICKETS_VIEW, session.user.rank)) {
redirect("/admin");
}
const t = await getTranslations("pages.admin.helpTickets");
const raw = await searchParams;
const parsed = parseListParams(new URLSearchParams(raw));
const statusFilter = raw.filter_status || "open";
const conditions: Prisma.WebsiteHelpCenterTicketsWhereInput[] = [];
if (statusFilter === "open") {
conditions.push({ open: true });
} else if (statusFilter === "closed") {
conditions.push({ open: false });
}
if (parsed.search.trim()) {
const q = parsed.search.trim();
const asId = /^\d+$/.test(q) ? BigInt(q) : null;
const matchingUsers = await prisma.user
.findMany({
where: { username: { contains: q } },
select: { id: true },
take: 50,
})
.catch(() => []);
conditions.push({
OR: [
{ title: { contains: q } },
{ content: { contains: q } },
...(matchingUsers.length > 0
? [{ userId: { in: matchingUsers.map((u) => u.id) } }]
: []),
...(asId !== null ? [{ id: asId }] : []),
],
});
}
const where: Prisma.WebsiteHelpCenterTicketsWhereInput =
conditions.length === 0
? {}
: conditions.length === 1
? conditions[0]
: { AND: conditions };
const SORT_MAP: Record<
string,
Prisma.WebsiteHelpCenterTicketsOrderByWithRelationInput
> = {
title: { title: "asc" },
open: { open: "desc" },
user: { userId: "asc" },
date: { createdAt: "desc" },
updated: { updatedAt: "desc" },
id: { id: "desc" },
};
const baseOrder = SORT_MAP[parsed.sort ?? "updated"] ?? { updatedAt: "desc" };
const orderField = Object.keys(baseOrder)[0] as keyof typeof baseOrder;
const orderBy = {
[orderField]: parsed.order,
} as Prisma.WebsiteHelpCenterTicketsOrderByWithRelationInput;
const [total, openCount, closedCount] = await Promise.all([
prisma.websiteHelpCenterTickets.count({ where }).catch(() => 0),
prisma.websiteHelpCenterTickets
.count({ where: { open: true } })
.catch(() => 0),
prisma.websiteHelpCenterTickets
.count({ where: { open: false } })
.catch(() => 0),
]);
const pagination = calcPagination(total, parsed.page, parsed.perPage);
const tickets = await prisma.websiteHelpCenterTickets
.findMany({
where,
orderBy,
skip: pagination.offset,
take: pagination.perPage,
select: {
id: true,
userId: true,
title: true,
open: true,
createdAt: true,
updatedAt: true,
},
})
.catch(() => []);
const ticketIds = tickets.map((ticket) => ticket.id);
const userIds = [
...new Set(
tickets.map((ticket) => ticket.userId).filter((id): id is number => id != null),
),
];
const [replyGroups, users] = await Promise.all([
ticketIds.length > 0
? prisma.websiteHelpCenterTicketReplies
.groupBy({
by: ["ticketId"],
where: { ticketId: { in: ticketIds } },
_count: true,
})
.catch(() => [])
: Promise.resolve([]),
userIds.length > 0
? prisma.user
.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
.catch(() => [])
: Promise.resolve([]),
]);
const replyCountByTicket = new Map(
replyGroups.map((g) => [String(g.ticketId), g._count]),
);
const usernameById = new Map(users.map((u) => [u.id, u.username]));
const rows: HelpTicketRow[] = tickets.map((ticket) => ({
id: String(ticket.id),
title: ticket.title,
user:
ticket.userId != null
? (usernameById.get(ticket.userId) ?? `#${ticket.userId}`)
: "—",
userId: ticket.userId,
replies: replyCountByTicket.get(String(ticket.id)) ?? 0,
open: ticket.open,
date: fromDate(ticket.createdAt),
updated: fromDate(ticket.updatedAt),
}));
return (
<div className="space-y-6">
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5">
<StatusCard label={t("statusOpen")} value={openCount} icon="🎫" />
<StatusCard label={t("statusClosed")} value={closedCount} icon="✅" />
</div>
{total === 0 && !parsed.search && statusFilter === "open" ? (
<div className="admin-empty">{t("noTickets")}</div>
) : (
<HelpTicketsTable
data={{
rows,
total,
page: pagination.page,
perPage: pagination.perPage,
lastPage: pagination.lastPage,
}}
/>
)}
</div>
);
}
+22 -5
View File
@@ -1,21 +1,36 @@
import { env } from "@/env";
import { apiJson } from "@/lib/api";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/redis";
import { rcon } from "@/lib/services/rcon";
export const dynamic = "force-dynamic";
/**
* Ops health probe: database reachability, emulator RCON reachability, SMTP
* (when configured), and runtime info. Returns HTTP 200 always (read the
* `status`/`database` fields), so it's safe for uptime monitors that only care
* about reachability.
* Ops health probe: database reachability, Redis (when configured), emulator
* RCON, SMTP (when configured), and runtime info. Returns HTTP 200 always
* (read the `status`/`database` fields), so it's safe for uptime monitors that
* only care about reachability.
*/
export async function GET() {
const database = await prisma.$queryRaw`SELECT 1`
.then(() => true)
.catch(() => false);
let redisOk: boolean | null = null;
if (env.REDIS_URL) {
if (!redis) {
redisOk = false;
} else {
try {
const pong = await redis.ping();
redisOk = pong === "PONG";
} catch {
redisOk = false;
}
}
}
const emulator = await rcon.send("ping", null).catch(() => false);
let smtp = null;
@@ -35,9 +50,11 @@ export async function GET() {
.catch(() => false);
}
const degraded = !database || redisOk === false;
return apiJson({
status: database ? "ok" : "degraded",
status: degraded ? "degraded" : "ok",
database,
redis: redisOk,
emulator,
smtp,
node: process.version,
+5
View File
@@ -7,6 +7,7 @@
import { apiError, apiJson, positiveBigInt } from "@/lib/api";
import { bearerUserId } from "@/lib/api-auth";
import { prisma } from "@/lib/prisma";
import { rateLimit } from "@/lib/rate-limit";
import { createOwnedTicketReply } from "@/lib/services/ticket-replies";
export const dynamic = "force-dynamic";
@@ -19,6 +20,10 @@ export async function POST(
const uid = await bearerUserId(req);
if (!uid) return apiError("Unauthorized", 401);
if (!(await rateLimit(`api-ticket-reply:${uid}`, 10, 60_000)).ok) {
return apiError("Too many requests", 429);
}
const { id } = await params;
const ticketId = positiveBigInt(id);
if (!ticketId) return apiError("Invalid ticket id", 422);
+5
View File
@@ -7,6 +7,7 @@
import { apiError, apiJson, positiveBigInt } from "@/lib/api";
import { bearerUserId } from "@/lib/api-auth";
import { prisma } from "@/lib/prisma";
import { rateLimit } from "@/lib/rate-limit";
export const dynamic = "force-dynamic";
@@ -40,6 +41,10 @@ export async function POST(req: Request) {
const uid = await bearerUserId(req);
if (!uid) return apiError("Unauthorized", 401);
if (!(await rateLimit(`api-ticket:${uid}`, 5, 60_000)).ok) {
return apiError("Too many requests", 429);
}
const body = (await req.json().catch(() => ({}))) as {
title?: unknown;
content?: unknown;