feat: jwt cache, redis health, help-ticket admin, and write rate limits
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:
1 parent
3bb96eb6f3
commit
968ca15c27
23 files changed
+1344
-205
No files matched your search
@@ -0,0 +1,136 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { PERMS } from "@/lib/permissions";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { adminAction } from "@/lib/safe-action";
|
||||
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
||||
import { logAudit } from "@/lib/services/audit";
|
||||
|
||||
const ticketIdField = z
|
||||
.union([z.string(), z.number(), z.bigint()])
|
||||
.transform((v) => BigInt(String(v)));
|
||||
|
||||
const replyHelpCenterTicketSchema = z.object({
|
||||
ticketId: ticketIdField,
|
||||
content: z.string().min(1).max(5000),
|
||||
});
|
||||
|
||||
const helpCenterTicketIdSchema = z.object({
|
||||
ticketId: ticketIdField,
|
||||
});
|
||||
|
||||
function revalidateHelpCenterTicketPaths(ticketId: bigint) {
|
||||
const id = String(ticketId);
|
||||
revalidatePath("/admin/help-tickets");
|
||||
revalidatePath(`/admin/help-tickets/${id}`);
|
||||
revalidatePath("/help/tickets");
|
||||
revalidatePath(`/help/tickets/${id}`);
|
||||
}
|
||||
|
||||
export const replyHelpCenterTicket = adminAction(
|
||||
{ permission: PERMS.TICKETS_EDIT, schema: replyHelpCenterTicketSchema },
|
||||
async (ctx) => {
|
||||
const ticketId = ctx.data.ticketId;
|
||||
const ticket = await prisma.websiteHelpCenterTickets.findUnique({
|
||||
where: { id: ticketId },
|
||||
select: { id: true, open: true },
|
||||
});
|
||||
|
||||
if (!ticket) throw new ActionError("Ticket not found");
|
||||
|
||||
const now = new Date();
|
||||
const staffId = Number(ctx.session.user.id);
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.websiteHelpCenterTicketReplies.create({
|
||||
data: {
|
||||
ticketId,
|
||||
userId: staffId,
|
||||
content: ctx.data.content.trim(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
prisma.websiteHelpCenterTickets.update({
|
||||
where: { id: ticketId },
|
||||
data: { updatedAt: now },
|
||||
}),
|
||||
]);
|
||||
|
||||
logAudit({
|
||||
userId: staffId,
|
||||
action: "help_center_ticket_reply",
|
||||
target: "WebsiteHelpCenterTickets",
|
||||
targetId: Number(ticketId),
|
||||
});
|
||||
|
||||
revalidateHelpCenterTicketPaths(ticketId);
|
||||
return actionOk();
|
||||
},
|
||||
);
|
||||
|
||||
export const closeHelpCenterTicket = adminAction(
|
||||
{ permission: PERMS.TICKETS_EDIT, schema: helpCenterTicketIdSchema },
|
||||
async (ctx) => {
|
||||
const ticketId = ctx.data.ticketId;
|
||||
const ticket = await prisma.websiteHelpCenterTickets.findUnique({
|
||||
where: { id: ticketId },
|
||||
select: { id: true, open: true },
|
||||
});
|
||||
|
||||
if (!ticket) throw new ActionError("Ticket not found");
|
||||
if (!ticket.open) throw new ActionError("Ticket is already closed");
|
||||
|
||||
const now = new Date();
|
||||
await prisma.websiteHelpCenterTickets.update({
|
||||
where: { id: ticketId },
|
||||
data: { open: false, updatedAt: now },
|
||||
});
|
||||
|
||||
logAudit({
|
||||
userId: Number(ctx.session.user.id),
|
||||
action: "help_center_ticket_close",
|
||||
target: "WebsiteHelpCenterTickets",
|
||||
targetId: Number(ticketId),
|
||||
before: { open: true },
|
||||
after: { open: false },
|
||||
});
|
||||
|
||||
revalidateHelpCenterTicketPaths(ticketId);
|
||||
return actionOk();
|
||||
},
|
||||
);
|
||||
|
||||
export const reopenHelpCenterTicket = adminAction(
|
||||
{ permission: PERMS.TICKETS_EDIT, schema: helpCenterTicketIdSchema },
|
||||
async (ctx) => {
|
||||
const ticketId = ctx.data.ticketId;
|
||||
const ticket = await prisma.websiteHelpCenterTickets.findUnique({
|
||||
where: { id: ticketId },
|
||||
select: { id: true, open: true },
|
||||
});
|
||||
|
||||
if (!ticket) throw new ActionError("Ticket not found");
|
||||
if (ticket.open) throw new ActionError("Ticket is already open");
|
||||
|
||||
const now = new Date();
|
||||
await prisma.websiteHelpCenterTickets.update({
|
||||
where: { id: ticketId },
|
||||
data: { open: true, updatedAt: now },
|
||||
});
|
||||
|
||||
logAudit({
|
||||
userId: Number(ctx.session.user.id),
|
||||
action: "help_center_ticket_reopen",
|
||||
target: "WebsiteHelpCenterTickets",
|
||||
targetId: Number(ticketId),
|
||||
before: { open: false },
|
||||
after: { open: true },
|
||||
});
|
||||
|
||||
revalidateHelpCenterTicketPaths(ticketId);
|
||||
return actionOk();
|
||||
},
|
||||
);
|
||||
@@ -4,13 +4,19 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
// The reaction set the UI offers. The action rejects anything outside this list
|
||||
// so the website_article_reactions.reaction VARCHAR(50) only ever holds known
|
||||
// values. Keep this in sync with REACTIONS in src/app/news/[slug]/page.tsx.
|
||||
const ALLOWED_REACTIONS = new Set(["like", "love", "wow"]);
|
||||
|
||||
type ReactionOutcome = "updated" | "invalid" | "not_found" | "error";
|
||||
type ReactionOutcome =
|
||||
| "updated"
|
||||
| "invalid"
|
||||
| "not_found"
|
||||
| "ratelimit"
|
||||
| "error";
|
||||
|
||||
function reactionRedirect(slug: string, outcome: ReactionOutcome): never {
|
||||
const path = slug ? `/news/${encodeURIComponent(slug)}` : "/news";
|
||||
@@ -50,58 +56,63 @@ export async function toggleReaction(formData: FormData): Promise<void> {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
const reaction = String(formData.get("reaction") ?? "")
|
||||
.normalize("NFC")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!ALLOWED_REACTIONS.has(reaction)) {
|
||||
outcome = "invalid";
|
||||
await clientIp();
|
||||
if (!(await rateLimit(`article-reaction:${userId}`, 30, 60_000)).ok) {
|
||||
outcome = "ratelimit";
|
||||
} else {
|
||||
const articleIdRaw = String(formData.get("articleId") ?? "")
|
||||
const reaction = String(formData.get("reaction") ?? "")
|
||||
.normalize("NFC")
|
||||
.trim();
|
||||
if (!/^\d+$/.test(articleIdRaw)) {
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!ALLOWED_REACTIONS.has(reaction)) {
|
||||
outcome = "invalid";
|
||||
} else {
|
||||
const articleId = BigInt(articleIdRaw);
|
||||
|
||||
const article = await prisma.websiteArticles.findUnique({
|
||||
where: { id: articleId },
|
||||
select: { slug: true },
|
||||
});
|
||||
if (!article) {
|
||||
outcome = "not_found";
|
||||
const articleIdRaw = String(formData.get("articleId") ?? "")
|
||||
.normalize("NFC")
|
||||
.trim();
|
||||
if (!/^\d+$/.test(articleIdRaw)) {
|
||||
outcome = "invalid";
|
||||
} else {
|
||||
slug = article.slug;
|
||||
const articleId = BigInt(articleIdRaw);
|
||||
|
||||
const existing = await prisma.websiteArticleReactions.findFirst({
|
||||
where: { userId, articleId, reaction },
|
||||
select: { id: true, active: true },
|
||||
const article = await prisma.websiteArticles.findUnique({
|
||||
where: { id: articleId },
|
||||
select: { slug: true },
|
||||
});
|
||||
|
||||
if (existing?.active) {
|
||||
await prisma.websiteArticleReactions.update({
|
||||
where: { id: existing.id },
|
||||
data: { active: false },
|
||||
});
|
||||
if (!article) {
|
||||
outcome = "not_found";
|
||||
} else {
|
||||
await prisma.websiteArticleReactions.updateMany({
|
||||
where: { userId, articleId, active: true },
|
||||
data: { active: false },
|
||||
slug = article.slug;
|
||||
|
||||
const existing = await prisma.websiteArticleReactions.findFirst({
|
||||
where: { userId, articleId, reaction },
|
||||
select: { id: true, active: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
if (existing?.active) {
|
||||
await prisma.websiteArticleReactions.update({
|
||||
where: { id: existing.id },
|
||||
data: { active: true },
|
||||
data: { active: false },
|
||||
});
|
||||
} else {
|
||||
await prisma.websiteArticleReactions.create({
|
||||
data: { userId, articleId, reaction, active: true },
|
||||
await prisma.websiteArticleReactions.updateMany({
|
||||
where: { userId, articleId, active: true },
|
||||
data: { active: false },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await prisma.websiteArticleReactions.update({
|
||||
where: { id: existing.id },
|
||||
data: { active: true },
|
||||
});
|
||||
} else {
|
||||
await prisma.websiteArticleReactions.create({
|
||||
data: { userId, articleId, reaction, active: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
outcome = "updated";
|
||||
}
|
||||
outcome = "updated";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+95
-86
@@ -4,7 +4,7 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { clientIp } from "@/lib/rate-limit";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
import { rcon } from "@/lib/services/rcon";
|
||||
import { type CurrencyName, sendCurrency } from "@/lib/services/send-currency";
|
||||
|
||||
@@ -40,6 +40,7 @@ export async function claimReferral(_formData: FormData): Promise<void> {
|
||||
| "not_enough"
|
||||
| "no_referrals"
|
||||
| "bad_config"
|
||||
| "ratelimit"
|
||||
| "error" = "error";
|
||||
|
||||
try {
|
||||
@@ -53,97 +54,105 @@ export async function claimReferral(_formData: FormData): Promise<void> {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
// Reward configuration (CMS-owned website_settings). AtomCMS defaults:
|
||||
// 5 referrals needed, 30 diamonds reward.
|
||||
const [neededRaw, amountRaw, currencyRaw] = await Promise.all([
|
||||
prisma.websiteSetting
|
||||
.findUnique({
|
||||
where: { key: "referrals_needed" },
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
prisma.websiteSetting
|
||||
.findUnique({
|
||||
where: { key: "referral_reward_amount" },
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
// The seeded key is referral_reward_currency_type; fall back to the
|
||||
// shorter referral_reward_currency name if that is what is configured.
|
||||
prisma.websiteSetting
|
||||
.findFirst({
|
||||
where: {
|
||||
key: {
|
||||
in: ["referral_reward_currency_type", "referral_reward_currency"],
|
||||
},
|
||||
},
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
]);
|
||||
|
||||
const needed = Number.parseInt(neededRaw?.value ?? "5", 10) || 5;
|
||||
const amount = Number.parseInt(amountRaw?.value ?? "30", 10);
|
||||
const currency = (currencyRaw?.value ?? "diamonds")
|
||||
.trim()
|
||||
.toLowerCase() as CurrencyName;
|
||||
|
||||
// The user's referral tally lives in user_referrals (one row per user).
|
||||
const referrals = await prisma.userReferrals
|
||||
.findFirst({
|
||||
where: { userId },
|
||||
select: { id: true, referralsTotal: true },
|
||||
orderBy: { id: "desc" },
|
||||
})
|
||||
.catch(() => null);
|
||||
|
||||
const total = referrals ? Number(referrals.referralsTotal) : 0;
|
||||
|
||||
if (!referrals || total <= 0) {
|
||||
outcome = "no_referrals";
|
||||
} else if (total < needed) {
|
||||
outcome = "not_enough";
|
||||
} else if (!VALID_CURRENCIES.has(currency) || !(amount > 0)) {
|
||||
// Misconfigured reward — keep it conservative and grant nothing.
|
||||
outcome = "bad_config";
|
||||
await clientIp();
|
||||
if (!(await rateLimit(`referral-claim:${userId}`, 5, 60_000)).ok) {
|
||||
outcome = "ratelimit";
|
||||
} else {
|
||||
// Spend the threshold first so a concurrent double-submit can't claim
|
||||
// twice off the same balance, then deliver the reward and log it.
|
||||
await prisma.userReferrals.update({
|
||||
where: { id: referrals.id },
|
||||
data: { referralsTotal: { decrement: needed } },
|
||||
});
|
||||
|
||||
try {
|
||||
await sendCurrency({ rcon, db: prisma }, userId, currency, amount);
|
||||
} catch {
|
||||
// sendCurrency already falls back to a direct DB write; if it still
|
||||
// throws the spend stands. Roll the threshold back so the user isn't
|
||||
// charged for an undelivered reward.
|
||||
await prisma.userReferrals
|
||||
.update({
|
||||
where: { id: referrals.id },
|
||||
data: { referralsTotal: { increment: needed } },
|
||||
// Reward configuration (CMS-owned website_settings). AtomCMS defaults:
|
||||
// 5 referrals needed, 30 diamonds reward.
|
||||
const [neededRaw, amountRaw, currencyRaw] = await Promise.all([
|
||||
prisma.websiteSetting
|
||||
.findUnique({
|
||||
where: { key: "referrals_needed" },
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => {});
|
||||
outcome = "error";
|
||||
throw new Error("currency-delivery-failed");
|
||||
}
|
||||
.catch(() => null),
|
||||
prisma.websiteSetting
|
||||
.findUnique({
|
||||
where: { key: "referral_reward_amount" },
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
// The seeded key is referral_reward_currency_type; fall back to the
|
||||
// shorter referral_reward_currency name if that is what is configured.
|
||||
prisma.websiteSetting
|
||||
.findFirst({
|
||||
where: {
|
||||
key: {
|
||||
in: [
|
||||
"referral_reward_currency_type",
|
||||
"referral_reward_currency",
|
||||
],
|
||||
},
|
||||
},
|
||||
select: { value: true },
|
||||
})
|
||||
.catch(() => null),
|
||||
]);
|
||||
|
||||
await prisma.claimedReferralLogs
|
||||
.create({
|
||||
data: {
|
||||
userId,
|
||||
ipAddress: await clientIp(),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
const needed = Number.parseInt(neededRaw?.value ?? "5", 10) || 5;
|
||||
const amount = Number.parseInt(amountRaw?.value ?? "30", 10);
|
||||
const currency = (currencyRaw?.value ?? "diamonds")
|
||||
.trim()
|
||||
.toLowerCase() as CurrencyName;
|
||||
|
||||
// The user's referral tally lives in user_referrals (one row per user).
|
||||
const referrals = await prisma.userReferrals
|
||||
.findFirst({
|
||||
where: { userId },
|
||||
select: { id: true, referralsTotal: true },
|
||||
orderBy: { id: "desc" },
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort audit log; the reward already landed.
|
||||
.catch(() => null);
|
||||
|
||||
const total = referrals ? Number(referrals.referralsTotal) : 0;
|
||||
|
||||
if (!referrals || total <= 0) {
|
||||
outcome = "no_referrals";
|
||||
} else if (total < needed) {
|
||||
outcome = "not_enough";
|
||||
} else if (!VALID_CURRENCIES.has(currency) || !(amount > 0)) {
|
||||
// Misconfigured reward — keep it conservative and grant nothing.
|
||||
outcome = "bad_config";
|
||||
} else {
|
||||
// Spend the threshold first so a concurrent double-submit can't claim
|
||||
// twice off the same balance, then deliver the reward and log it.
|
||||
await prisma.userReferrals.update({
|
||||
where: { id: referrals.id },
|
||||
data: { referralsTotal: { decrement: needed } },
|
||||
});
|
||||
|
||||
outcome = "claimed";
|
||||
try {
|
||||
await sendCurrency({ rcon, db: prisma }, userId, currency, amount);
|
||||
} catch {
|
||||
// sendCurrency already falls back to a direct DB write; if it still
|
||||
// throws the spend stands. Roll the threshold back so the user isn't
|
||||
// charged for an undelivered reward.
|
||||
await prisma.userReferrals
|
||||
.update({
|
||||
where: { id: referrals.id },
|
||||
data: { referralsTotal: { increment: needed } },
|
||||
})
|
||||
.catch(() => {});
|
||||
outcome = "error";
|
||||
throw new Error("currency-delivery-failed");
|
||||
}
|
||||
|
||||
await prisma.claimedReferralLogs
|
||||
.create({
|
||||
data: {
|
||||
userId,
|
||||
ipAddress: await clientIp(),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort audit log; the reward already landed.
|
||||
});
|
||||
|
||||
outcome = "claimed";
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// redirect() throws a NEXT_REDIRECT control-flow signal — re-throw it so the
|
||||
|
||||
+13
-1
@@ -1,11 +1,13 @@
|
||||
"use server";
|
||||
|
||||
import { auth, signOut } from "@/lib/auth";
|
||||
import { invalidateJwtVersionCache } from "@/lib/auth/jwt-version-cache";
|
||||
import { personalTokenScope } from "@/lib/auth/personal-token-scope";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
/**
|
||||
* Invalidate every CMS JWT for the signed-in user by bumping website_jwt_version,
|
||||
* then end the current browser session too.
|
||||
* revoke personal access tokens, then end the current browser session too.
|
||||
*/
|
||||
export async function signOutEverywhere(): Promise<void> {
|
||||
const session = await auth();
|
||||
@@ -20,6 +22,16 @@ export async function signOutEverywhere(): Promise<void> {
|
||||
where: { id: userId },
|
||||
data: { websiteJwtVersion: { increment: 1 } },
|
||||
});
|
||||
await invalidateJwtVersionCache(userId);
|
||||
} catch {
|
||||
/* still continue */
|
||||
}
|
||||
|
||||
// Revoke API bearer tokens (Sanctum / personal_access_tokens).
|
||||
try {
|
||||
await prisma.personalAccessTokens.deleteMany({
|
||||
where: personalTokenScope(userId),
|
||||
});
|
||||
} catch {
|
||||
/* still sign out locally */
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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" } },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -97,13 +97,18 @@ export const ADMIN_HUBS: AdminHubDefinition[] = [
|
||||
titleKey: "tickets",
|
||||
subtitleKey: "ticketsSubtitle",
|
||||
icon: Ticket,
|
||||
prefixes: ["/admin/tickets"],
|
||||
prefixes: ["/admin/tickets", "/admin/help-tickets"],
|
||||
tabs: [
|
||||
{
|
||||
href: "/admin/tickets",
|
||||
labelKey: "tickets",
|
||||
match: ["/admin/tickets"],
|
||||
},
|
||||
{
|
||||
href: "/admin/help-tickets",
|
||||
labelKey: "helpTickets",
|
||||
match: ["/admin/help-tickets"],
|
||||
},
|
||||
{ href: "/admin/tickets/templates", labelKey: "templates" },
|
||||
],
|
||||
},
|
||||
@@ -285,7 +290,7 @@ export const ADMIN_NAV_GROUPS: AdminNavGroup[] = [
|
||||
href: "/admin/tickets",
|
||||
labelKey: "tickets",
|
||||
icon: Ticket,
|
||||
matchPrefixes: ["/admin/tickets"],
|
||||
matchPrefixes: ["/admin/tickets", "/admin/help-tickets"],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+76
-71
@@ -4,6 +4,7 @@ import Discord from "next-auth/providers/discord";
|
||||
import Google from "next-auth/providers/google";
|
||||
import { env } from "@/env";
|
||||
import { LaravelEncrypter } from "@/lib/auth/laravel-encrypter";
|
||||
import { getCachedJwtVersion } from "@/lib/auth/jwt-version-cache";
|
||||
import { checkLogin } from "@/lib/auth/password";
|
||||
import { verifyTotp } from "@/lib/auth/totp";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
@@ -210,6 +211,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
(user as { jwtVersion?: number }).jwtVersion ??
|
||||
token.jwtVersion ??
|
||||
0;
|
||||
token.jwtCheckedAt = Date.now();
|
||||
}
|
||||
|
||||
if (user && account?.provider === "credentials") {
|
||||
@@ -217,29 +219,58 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
return token;
|
||||
}
|
||||
|
||||
const requireLink = await siteSettings.getBool(
|
||||
"oauth_require_link",
|
||||
false,
|
||||
);
|
||||
// OAuth account linking only when establishing a session — not on
|
||||
// every subsequent request (avoids siteSettings + DB on each hit).
|
||||
if (user || account) {
|
||||
const requireLink = await siteSettings.getBool(
|
||||
"oauth_require_link",
|
||||
false,
|
||||
);
|
||||
|
||||
// Try Discord ID via SocialAccounts (always allowed, even when requireLink is true).
|
||||
if (
|
||||
!token.sub &&
|
||||
account?.provider === "discord" &&
|
||||
account.providerAccountId
|
||||
) {
|
||||
try {
|
||||
const linked = await prisma.socialAccounts.findUnique({
|
||||
where: {
|
||||
provider_providerId: {
|
||||
provider: "discord",
|
||||
providerId: account.providerAccountId,
|
||||
// Try Discord ID via SocialAccounts (always allowed, even when requireLink is true).
|
||||
if (
|
||||
!token.sub &&
|
||||
account?.provider === "discord" &&
|
||||
account.providerAccountId
|
||||
) {
|
||||
try {
|
||||
const linked = await prisma.socialAccounts.findUnique({
|
||||
where: {
|
||||
provider_providerId: {
|
||||
provider: "discord",
|
||||
providerId: account.providerAccountId,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (linked) {
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: Number(linked.userId) },
|
||||
});
|
||||
if (linked) {
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: Number(linked.userId) },
|
||||
select: {
|
||||
id: true,
|
||||
rank: true,
|
||||
username: true,
|
||||
websiteJwtVersion: true,
|
||||
},
|
||||
});
|
||||
if (dbUser) {
|
||||
token.sub = String(dbUser.id);
|
||||
token.rank = dbUser.rank;
|
||||
token.name = dbUser.username;
|
||||
token.jwtVersion = dbUser.websiteJwtVersion;
|
||||
token.jwtCheckedAt = Date.now();
|
||||
return token;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// leave token as-is on lookup failure
|
||||
}
|
||||
}
|
||||
|
||||
// Email-based binding: only when requireLink is off AND account has no 2FA.
|
||||
if (!requireLink && user?.email && !token.sub) {
|
||||
try {
|
||||
const dbUser = await prisma.user.findFirst({
|
||||
where: { mail: user.email, twoFactorConfirmedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
rank: true,
|
||||
@@ -252,59 +283,33 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
token.rank = dbUser.rank;
|
||||
token.name = dbUser.username;
|
||||
token.jwtVersion = dbUser.websiteJwtVersion;
|
||||
token.jwtCheckedAt = Date.now();
|
||||
}
|
||||
} catch {
|
||||
// leave token as-is on lookup failure
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Re-check jwt version at most once per minute (memory/Redis cached).
|
||||
if (token.sub && !token.invalid) {
|
||||
const lastCheck =
|
||||
typeof token.jwtCheckedAt === "number" ? token.jwtCheckedAt : 0;
|
||||
if (Date.now() - lastCheck >= 60_000) {
|
||||
try {
|
||||
const version = await getCachedJwtVersion(Number(token.sub));
|
||||
if (
|
||||
version === null ||
|
||||
(token.jwtVersion ?? 0) !== version
|
||||
) {
|
||||
token.invalid = true;
|
||||
delete token.sub;
|
||||
return token;
|
||||
}
|
||||
token.jwtCheckedAt = Date.now();
|
||||
} catch {
|
||||
/* keep session on transient DB/cache errors */
|
||||
}
|
||||
} catch {
|
||||
// leave token as-is on lookup failure
|
||||
}
|
||||
}
|
||||
|
||||
// Email-based binding: only when requireLink is off AND account has no 2FA.
|
||||
if (!requireLink && user?.email && !token.sub) {
|
||||
try {
|
||||
const dbUser = await prisma.user.findFirst({
|
||||
where: { mail: user.email, twoFactorConfirmedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
rank: true,
|
||||
username: true,
|
||||
websiteJwtVersion: true,
|
||||
},
|
||||
});
|
||||
if (dbUser) {
|
||||
token.sub = String(dbUser.id);
|
||||
token.rank = dbUser.rank;
|
||||
token.name = dbUser.username;
|
||||
token.jwtVersion = dbUser.websiteJwtVersion;
|
||||
}
|
||||
} catch {
|
||||
// leave token as-is on lookup failure
|
||||
}
|
||||
}
|
||||
|
||||
if (token.sub && !token.invalid) {
|
||||
try {
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: Number(token.sub) },
|
||||
select: {
|
||||
websiteJwtVersion: true,
|
||||
rank: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
if (
|
||||
!dbUser ||
|
||||
(token.jwtVersion ?? 0) !== dbUser.websiteJwtVersion
|
||||
) {
|
||||
token.invalid = true;
|
||||
delete token.sub;
|
||||
return token;
|
||||
}
|
||||
token.rank = dbUser.rank;
|
||||
token.name = dbUser.username;
|
||||
} catch {
|
||||
/* keep session on transient DB errors */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockFindUnique = vi.hoisted(() => vi.fn());
|
||||
const mockRedisGet = vi.hoisted(() => vi.fn());
|
||||
const mockRedisSetex = vi.hoisted(() => vi.fn());
|
||||
const mockRedisDel = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: mockFindUnique },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/redis", () => ({
|
||||
redis: {
|
||||
get: mockRedisGet,
|
||||
setex: mockRedisSetex,
|
||||
del: mockRedisDel,
|
||||
},
|
||||
}));
|
||||
|
||||
describe("jwt-version-cache", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
mockRedisGet.mockResolvedValue(null);
|
||||
mockRedisSetex.mockResolvedValue("OK");
|
||||
mockRedisDel.mockResolvedValue(1);
|
||||
});
|
||||
|
||||
it("returns DB version and caches it", async () => {
|
||||
mockFindUnique.mockResolvedValue({ websiteJwtVersion: 3 });
|
||||
const { getCachedJwtVersion } = await import("./jwt-version-cache");
|
||||
await expect(getCachedJwtVersion(42)).resolves.toBe(3);
|
||||
expect(mockFindUnique).toHaveBeenCalledTimes(1);
|
||||
await expect(getCachedJwtVersion(42)).resolves.toBe(3);
|
||||
expect(mockFindUnique).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("invalidates memory and redis entries", async () => {
|
||||
mockFindUnique.mockResolvedValue({ websiteJwtVersion: 1 });
|
||||
const { getCachedJwtVersion, invalidateJwtVersionCache } = await import(
|
||||
"./jwt-version-cache"
|
||||
);
|
||||
await getCachedJwtVersion(7);
|
||||
await invalidateJwtVersionCache(7);
|
||||
expect(mockRedisDel).toHaveBeenCalled();
|
||||
mockFindUnique.mockResolvedValue({ websiteJwtVersion: 2 });
|
||||
await expect(getCachedJwtVersion(7)).resolves.toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import "server-only";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
const MEMORY_TTL_MS = 60_000;
|
||||
const REDIS_TTL_SEC = 60;
|
||||
const memory = new Map<number, { version: number; expiresAt: number }>();
|
||||
|
||||
function redisKey(userId: number): string {
|
||||
return `jwtver:${userId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached `users.website_jwt_version` for Auth.js JWT validation.
|
||||
* Avoids a DB round-trip on every authenticated request.
|
||||
*/
|
||||
export async function getCachedJwtVersion(
|
||||
userId: number,
|
||||
): Promise<number | null> {
|
||||
if (!Number.isInteger(userId) || userId <= 0) return null;
|
||||
|
||||
const now = Date.now();
|
||||
const hit = memory.get(userId);
|
||||
if (hit && hit.expiresAt > now) return hit.version;
|
||||
|
||||
if (redis) {
|
||||
try {
|
||||
const raw = await redis.get(redisKey(userId));
|
||||
if (raw !== null && raw !== undefined) {
|
||||
const version = Number.parseInt(raw, 10);
|
||||
if (Number.isFinite(version)) {
|
||||
memory.set(userId, { version, expiresAt: now + MEMORY_TTL_MS });
|
||||
return version;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* fall through to DB */
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const row = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { websiteJwtVersion: true },
|
||||
});
|
||||
if (!row) return null;
|
||||
const version = row.websiteJwtVersion;
|
||||
memory.set(userId, { version, expiresAt: now + MEMORY_TTL_MS });
|
||||
if (redis) {
|
||||
try {
|
||||
await redis.setex(redisKey(userId), REDIS_TTL_SEC, String(version));
|
||||
} catch {
|
||||
/* non-critical */
|
||||
}
|
||||
}
|
||||
return version;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Call after bumping website_jwt_version so other instances drop sessions ASAP. */
|
||||
export async function invalidateJwtVersionCache(userId: number): Promise<void> {
|
||||
memory.delete(userId);
|
||||
if (redis) {
|
||||
try {
|
||||
await redis.del(redisKey(userId));
|
||||
} catch {
|
||||
/* non-critical */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ describe("production deploy workflow", () => {
|
||||
expect(deployJob).toContain('ln -sfn "${LIVE}/.env"');
|
||||
expect(deployJob).toContain("-e storage");
|
||||
expect(deployJob).toContain("DATABASE_POOL_SIZE=");
|
||||
expect(deployJob).toContain("REDIS_URL is unset");
|
||||
expect(deployJob).not.toContain("SKIP_ENV_VALIDATION=1");
|
||||
expect(deployJob).toContain("pnpm install --frozen-lockfile");
|
||||
});
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ function createRedis(): Redis | null {
|
||||
) {
|
||||
globalForRedis.redisMissingWarned = true;
|
||||
console.error(
|
||||
"[redis] REDIS_URL is unset in production. Rate limits and shared caches fall back to in-process memory and will not work correctly across multiple instances.",
|
||||
"[redis] REDIS_URL is unset in production. Rate limits, site-settings cache, and JWT session invalidation fall back to in-process memory and will not work correctly across multiple instances or restarts. Set REDIS_URL in .env.",
|
||||
);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -1001,6 +1001,7 @@
|
||||
"writeableBoxes": "Writeable boxes",
|
||||
"photos": "Photos",
|
||||
"tickets": "Tickets",
|
||||
"helpTickets": "Help center tickets",
|
||||
"events": "Events",
|
||||
"polls": "Polls",
|
||||
"banners": "Banners",
|
||||
@@ -1523,6 +1524,41 @@
|
||||
"colDate": "Date",
|
||||
"meta": "by {user} · {count} msg · {category}"
|
||||
},
|
||||
"helpTickets": {
|
||||
"title": "Help center tickets",
|
||||
"subtitle": "Player tickets from /help/tickets",
|
||||
"noTickets": "No open help center tickets",
|
||||
"searchPlaceholder": "Search title, user or ID…",
|
||||
"presetOpen": "Open",
|
||||
"presetAll": "All",
|
||||
"statusOpen": "Open",
|
||||
"statusClosed": "Closed",
|
||||
"colTicket": "Ticket",
|
||||
"colStatus": "Status",
|
||||
"colUser": "User",
|
||||
"colCreated": "Created",
|
||||
"colUpdated": "Updated",
|
||||
"meta": "by {user} · {count} replies",
|
||||
"backToList": "Back to list",
|
||||
"threadTitle": "Conversation",
|
||||
"staffBadge": "Staff",
|
||||
"replyPlaceholder": "Reply as staff…",
|
||||
"replySubmit": "Send reply",
|
||||
"replyHint": "Ctrl+Enter to send.",
|
||||
"closeSubmit": "Close ticket",
|
||||
"reopenSubmit": "Reopen ticket",
|
||||
"closedHint": "This ticket is closed.",
|
||||
"actionsTitle": "Actions",
|
||||
"requesterTitle": "Requester",
|
||||
"detailsTitle": "Details",
|
||||
"rankLabel": "Rank {rank}",
|
||||
"messageCountLabel": "Messages",
|
||||
"success": {
|
||||
"replied": "Reply sent.",
|
||||
"closed": "Ticket closed.",
|
||||
"reopened": "Ticket reopened."
|
||||
}
|
||||
},
|
||||
"cfh": {
|
||||
"title": "Call for Help",
|
||||
"subtitle": "In-game CFH / support tickets",
|
||||
@@ -2393,6 +2429,7 @@
|
||||
"eventTypes": "Event types",
|
||||
"polls": "Polls",
|
||||
"tickets": "Tickets",
|
||||
"helpTickets": "Help center tickets",
|
||||
"templates": "Templates",
|
||||
"directory": "Directory",
|
||||
"multiAccounts": "Multi-accounts",
|
||||
|
||||
@@ -953,6 +953,7 @@
|
||||
"writeableBoxes": "Box modificabili",
|
||||
"photos": "Foto",
|
||||
"tickets": "Ticket",
|
||||
"helpTickets": "Ticket centro assistenza",
|
||||
"events": "Eventi",
|
||||
"polls": "Sondaggi",
|
||||
"banners": "Banner",
|
||||
@@ -1479,6 +1480,41 @@
|
||||
"colDate": "Data",
|
||||
"meta": "di {user} · {count} msg · {category}"
|
||||
},
|
||||
"helpTickets": {
|
||||
"title": "Ticket centro assistenza",
|
||||
"subtitle": "Ticket dei giocatori da /help/tickets",
|
||||
"noTickets": "Nessun ticket aperto nel centro assistenza",
|
||||
"searchPlaceholder": "Cerca titolo, utente o ID…",
|
||||
"presetOpen": "Aperti",
|
||||
"presetAll": "Tutti",
|
||||
"statusOpen": "Aperti",
|
||||
"statusClosed": "Chiusi",
|
||||
"colTicket": "Ticket",
|
||||
"colStatus": "Stato",
|
||||
"colUser": "Utente",
|
||||
"colCreated": "Creato",
|
||||
"colUpdated": "Aggiornato",
|
||||
"meta": "di {user} · {count} risposte",
|
||||
"backToList": "Torna all'elenco",
|
||||
"threadTitle": "Conversazione",
|
||||
"staffBadge": "Staff",
|
||||
"replyPlaceholder": "Rispondi come staff…",
|
||||
"replySubmit": "Invia risposta",
|
||||
"replyHint": "Ctrl+Invio per inviare.",
|
||||
"closeSubmit": "Chiudi ticket",
|
||||
"reopenSubmit": "Riapri ticket",
|
||||
"closedHint": "Questo ticket è chiuso.",
|
||||
"actionsTitle": "Azioni",
|
||||
"requesterTitle": "Richiedente",
|
||||
"detailsTitle": "Dettagli",
|
||||
"rankLabel": "Rank {rank}",
|
||||
"messageCountLabel": "Messaggi",
|
||||
"success": {
|
||||
"replied": "Risposta inviata.",
|
||||
"closed": "Ticket chiuso.",
|
||||
"reopened": "Ticket riaperto."
|
||||
}
|
||||
},
|
||||
"cfh": {
|
||||
"title": "Call for Help",
|
||||
"subtitle": "Ticket CFH in-game",
|
||||
@@ -2628,6 +2664,7 @@
|
||||
"eventTypes": "Tipi evento",
|
||||
"polls": "Sondaggi",
|
||||
"tickets": "Ticket",
|
||||
"helpTickets": "Ticket centro assistenza",
|
||||
"templates": "Template",
|
||||
"directory": "Directory",
|
||||
"multiAccounts": "Multi-account",
|
||||
|
||||
@@ -998,6 +998,7 @@
|
||||
"writeableBoxes": "Bewerkbare boxes",
|
||||
"photos": "Foto's",
|
||||
"tickets": "Tickets",
|
||||
"helpTickets": "Helpcentrum-tickets",
|
||||
"events": "Events",
|
||||
"polls": "Polls",
|
||||
"banners": "Banners",
|
||||
@@ -2729,6 +2730,7 @@
|
||||
"eventTypes": "Evenementtypen",
|
||||
"polls": "Polls",
|
||||
"tickets": "Tickets",
|
||||
"helpTickets": "Helpcentrum-tickets",
|
||||
"templates": "Sjablonen",
|
||||
"directory": "Adresboek",
|
||||
"multiAccounts": "Multi-accounts",
|
||||
@@ -2815,6 +2817,41 @@
|
||||
"colDate": "Datum",
|
||||
"meta": "door {user} · {count} berichten · {category}"
|
||||
},
|
||||
"helpTickets": {
|
||||
"title": "Helpcentrum-tickets",
|
||||
"subtitle": "Spelertickets van /help/tickets",
|
||||
"noTickets": "Geen open helpcentrum-tickets",
|
||||
"searchPlaceholder": "Zoek op titel, gebruiker of ID…",
|
||||
"presetOpen": "Open",
|
||||
"presetAll": "Alle",
|
||||
"statusOpen": "Open",
|
||||
"statusClosed": "Gesloten",
|
||||
"colTicket": "Ticket",
|
||||
"colStatus": "Status",
|
||||
"colUser": "Gebruiker",
|
||||
"colCreated": "Aangemaakt",
|
||||
"colUpdated": "Bijgewerkt",
|
||||
"meta": "door {user} · {count} antwoorden",
|
||||
"backToList": "Terug naar lijst",
|
||||
"threadTitle": "Gesprek",
|
||||
"staffBadge": "Staff",
|
||||
"replyPlaceholder": "Antwoord als staff…",
|
||||
"replySubmit": "Antwoord versturen",
|
||||
"replyHint": "Ctrl+Enter om te versturen.",
|
||||
"closeSubmit": "Ticket sluiten",
|
||||
"reopenSubmit": "Ticket heropenen",
|
||||
"closedHint": "Dit ticket is gesloten.",
|
||||
"actionsTitle": "Acties",
|
||||
"requesterTitle": "Aanvrager",
|
||||
"detailsTitle": "Details",
|
||||
"rankLabel": "Rank {rank}",
|
||||
"messageCountLabel": "Berichten",
|
||||
"success": {
|
||||
"replied": "Antwoord verzonden.",
|
||||
"closed": "Ticket gesloten.",
|
||||
"reopened": "Ticket heropend."
|
||||
}
|
||||
},
|
||||
"cfh": {
|
||||
"title": "Call for Help",
|
||||
"subtitle": "In-game CFH / ondersteuningstickets",
|
||||
|
||||
Vendored
+1
@@ -10,6 +10,7 @@ declare module "next-auth/jwt" {
|
||||
interface JWT {
|
||||
rank?: number;
|
||||
jwtVersion?: number;
|
||||
jwtCheckedAt?: number;
|
||||
invalid?: boolean;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user