Security hardening: 12 improvements across the stack
1. env.ts: APP_KEY placeholder detection with validation 2. schema.prisma: password column widened to varchar(255) for argon2id 3. auth.ts: trustHost restricted to development only 4. next.config.ts: added CSP, HSTS, X-Frame-Options, and other security headers 5. api.ts: CORS restricted to APP_URL instead of wildcard 6. register-form.tsx: migrated from REST API fetch to server action (useActionState) 7. twofactor.ts + 2fa page: TOTP recovery codes (8 one-time codes, generated and displayed) 8. register.ts: password min length 8 + complexity requirements (upper, lower, digit) 9. register.ts + help-tickets.ts + radio-shouts.ts: Zod schema validation 10. rate-limit.ts: improved periodic cleanup with aggressive eviction at 10k buckets 11. guard.ts + admin actions: rate-limited admin actions (30 req/min per staff) 12. help-tickets.ts + radio-shouts.ts: content moderation via moderateOrThrow
This commit is contained in:
1 parent
a1950e5b65
commit
5628e7d6b7
19 files changed
+370
-220
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireStaff } from "@/lib/admin/guard";
|
||||
import { requireStaffRateLimited as requireStaff } from "@/lib/admin/guard";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { rcon } from "@/lib/services/rcon";
|
||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireStaff } from "@/lib/admin/guard";
|
||||
import { requireStaffRateLimited as requireStaff } from "@/lib/admin/guard";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { requireStaff } from "@/lib/admin/guard";
|
||||
import { requireStaff, requireStaffRateLimited } from "@/lib/admin/guard";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { rcon } from "@/lib/services/rcon";
|
||||
import { type CurrencyName, sendCurrency } from "@/lib/services/send-currency";
|
||||
@@ -10,7 +10,7 @@ import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||
const CURRENCIES: ReadonlySet<string> = new Set(["credits", "duckets", "diamonds", "points"]);
|
||||
|
||||
export async function giveCurrency(formData: FormData): Promise<void> {
|
||||
const staff = await requireStaff();
|
||||
const staff = await requireStaffRateLimited();
|
||||
const userId = Number(formData.get("userId"));
|
||||
const type = String(formData.get("type"));
|
||||
const amount = Number(formData.get("amount"));
|
||||
@@ -39,7 +39,7 @@ export async function setMotto(formData: FormData): Promise<void> {
|
||||
}
|
||||
|
||||
export async function setRank(formData: FormData): Promise<void> {
|
||||
const staff = await requireStaff();
|
||||
const staff = await requireStaffRateLimited();
|
||||
const userId = Number(formData.get("userId"));
|
||||
const rank = Number(formData.get("rank"));
|
||||
if (userId > 0 && rank > 0) {
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { moderateOrThrow } from "@/lib/services/moderation";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const ticketSchema = z.object({
|
||||
title: z.string().min(1, "Title is required").max(255),
|
||||
content: z.string().min(1, "Content is required").max(5000),
|
||||
});
|
||||
|
||||
export async function createTicket(formData: FormData): Promise<void> {
|
||||
// Re-read the session user id server-side; never trust a form-supplied id.
|
||||
@@ -10,9 +18,25 @@ export async function createTicket(formData: FormData): Promise<void> {
|
||||
const userId = Number(session?.user?.id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) return;
|
||||
|
||||
const title = String(formData.get("title") ?? "").trim().slice(0, 255);
|
||||
const content = String(formData.get("content") ?? "").trim().slice(0, 5000);
|
||||
if (!title || !content) return;
|
||||
const ip = await clientIp();
|
||||
if (!rateLimit(`ticket:${userId}`, 3, 60_000).ok) return;
|
||||
|
||||
const raw = {
|
||||
title: String(formData.get("title") ?? "").trim().slice(0, 255),
|
||||
content: String(formData.get("content") ?? "").trim().slice(0, 5000),
|
||||
};
|
||||
|
||||
const parsed = ticketSchema.safeParse(raw);
|
||||
if (!parsed.success) return;
|
||||
|
||||
const { title, content } = parsed.data;
|
||||
|
||||
// Moderation check
|
||||
try {
|
||||
await moderateOrThrow(`${title} ${content}`);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await prisma.websiteHelpCenterTickets.create({
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { moderateOrThrow } from "@/lib/services/moderation";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
// radio_shouts.message is TEXT, but cap the write to keep shouts tweet-sized.
|
||||
const MESSAGE_MAX = 255;
|
||||
const shoutSchema = z.object({
|
||||
message: z.string().min(1, "Message is required").max(255),
|
||||
});
|
||||
|
||||
/**
|
||||
* Post a radio shout.
|
||||
@@ -20,10 +24,24 @@ export async function postShout(formData: FormData): Promise<void> {
|
||||
const userId = Number(session?.user?.id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) return;
|
||||
|
||||
const message = String(formData.get("message") ?? "")
|
||||
.trim()
|
||||
.slice(0, MESSAGE_MAX);
|
||||
if (!message) return;
|
||||
const ip = await clientIp();
|
||||
if (!rateLimit(`shout:${userId}`, 5, 30_000).ok) return;
|
||||
|
||||
const raw = {
|
||||
message: String(formData.get("message") ?? "").trim().slice(0, 255),
|
||||
};
|
||||
|
||||
const parsed = shoutSchema.safeParse(raw);
|
||||
if (!parsed.success) return;
|
||||
|
||||
const { message } = parsed.data;
|
||||
|
||||
// Moderation check
|
||||
try {
|
||||
await moderateOrThrow(message);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
try {
|
||||
|
||||
+74
-67
@@ -1,6 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
import { sendVerification } from "@/actions/email-verify";
|
||||
import { hashPassword } from "@/lib/auth/password";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
@@ -9,95 +10,101 @@ import { captchaConfig, verifyCaptcha } from "@/lib/services/captcha";
|
||||
import { checkVpn } from "@/lib/services/ip-lookup";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
const USERNAME_RE = /^[A-Za-z0-9_\-=?!@:.,]{3,25}$/;
|
||||
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
||||
const registerSchema = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(3, "Username must be at least 3 characters")
|
||||
.max(25, "Username must be at most 25 characters")
|
||||
.regex(/^[A-Za-z0-9_\-=?!@:.,]+$/, "Username contains invalid characters"),
|
||||
mail: z.string().email("Enter a valid email address"),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.regex(/[A-Z]/, "Password must contain at least one uppercase letter")
|
||||
.regex(/[a-z]/, "Password must contain at least one lowercase letter")
|
||||
.regex(/[0-9]/, "Password must contain at least one digit"),
|
||||
look: z.string().optional(),
|
||||
});
|
||||
|
||||
// A valid starter Habbo figure so the avatar renders in-client immediately.
|
||||
const DEFAULT_LOOK = "hr-100-.hd-180-1.ch-255-66.lg-280-110.sh-305-62";
|
||||
|
||||
export async function register(formData: FormData): Promise<void> {
|
||||
const username = String(formData.get("username") ?? "").trim();
|
||||
const mail = String(formData.get("mail") ?? "").trim().toLowerCase();
|
||||
const password = String(formData.get("password") ?? "");
|
||||
export async function register(prevState: string | null, formData: FormData): Promise<string | null> {
|
||||
const raw = {
|
||||
username: String(formData.get("username") ?? "").trim(),
|
||||
mail: String(formData.get("mail") ?? "").trim().toLowerCase(),
|
||||
password: String(formData.get("password") ?? ""),
|
||||
look: String(formData.get("look") ?? "").trim() || DEFAULT_LOOK,
|
||||
};
|
||||
|
||||
const parsed = registerSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
return parsed.error.errors[0]?.message ?? "Invalid input";
|
||||
}
|
||||
|
||||
const { username, mail, password, look } = parsed.data;
|
||||
const ip = await clientIp();
|
||||
|
||||
let error: string | null = null;
|
||||
if (!USERNAME_RE.test(username)) error = "Username must be 3-25 valid characters";
|
||||
else if (password.length < 6) error = "Password must be at least 6 characters";
|
||||
else if (!EMAIL_RE.test(mail)) error = "Enter a valid email address";
|
||||
|
||||
// Throttle sign-ups per IP (5 per 10 minutes) to curb account spam.
|
||||
if (!error && !rateLimit(`register:${ip}`, 5, 10 * 60_000).ok) {
|
||||
error = "Too many sign-up attempts. Please wait a few minutes and try again.";
|
||||
if (!rateLimit(`register:${ip}`, 5, 10 * 60_000).ok) {
|
||||
return "Too many sign-up attempts. Please wait a few minutes and try again.";
|
||||
}
|
||||
|
||||
// CAPTCHA (Turnstile / reCAPTCHA) — only enforced when configured in settings.
|
||||
if (!error) {
|
||||
const cfg = await captchaConfig();
|
||||
if (cfg.provider !== "none") {
|
||||
const token = String(formData.get(cfg.field) ?? "");
|
||||
if (!(await verifyCaptcha(token, ip))) error = "Captcha verification failed. Please try again.";
|
||||
}
|
||||
const cfg = await captchaConfig();
|
||||
if (cfg.provider !== "none") {
|
||||
const token = String(formData.get(cfg.field) ?? "");
|
||||
if (!(await verifyCaptcha(token, ip))) return "Captcha verification failed. Please try again.";
|
||||
}
|
||||
|
||||
// VPN/proxy block (only when enabled in /admin/vpn).
|
||||
if (!error && (await checkVpn(ip)).blocked) {
|
||||
error =
|
||||
(await siteSettings.get("vpn_block_message", "")) ||
|
||||
"Registrations from VPN/proxy connections are not allowed.";
|
||||
if ((await checkVpn(ip)).blocked) {
|
||||
return (
|
||||
await siteSettings.get("vpn_block_message", "")
|
||||
) || "Registrations from VPN/proxy connections are not allowed.";
|
||||
}
|
||||
|
||||
// Max accounts per IP (0 / unset = unlimited), mirrors AtomCMS.
|
||||
if (!error) {
|
||||
const max = Number(await siteSettings.get("max_accounts_per_ip", "0")) || 0;
|
||||
if (max > 0) {
|
||||
const count = await prisma.user.count({ where: { ipRegister: ip } }).catch(() => 0);
|
||||
if (count >= max) error = "You have reached the maximum number of accounts for your connection.";
|
||||
}
|
||||
const max = Number(await siteSettings.get("max_accounts_per_ip", "0")) || 0;
|
||||
if (max > 0) {
|
||||
const count = await prisma.user.count({ where: { ipRegister: ip } }).catch(() => 0);
|
||||
if (count >= max) return "You have reached the maximum number of accounts for your connection.";
|
||||
}
|
||||
|
||||
// Uniqueness check (kept out of the success path's try so NEXT_REDIRECT propagates).
|
||||
if (!error) {
|
||||
// Uniqueness check.
|
||||
try {
|
||||
const existing = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) return "That username is already taken";
|
||||
} catch {
|
||||
return "Registration is temporarily unavailable";
|
||||
}
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
try {
|
||||
const created = await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
password: await hashPassword(password),
|
||||
mail,
|
||||
accountCreated: now,
|
||||
ipRegister: ip,
|
||||
ipCurrent: ip,
|
||||
look,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
try {
|
||||
const existing = await prisma.user.findUnique({
|
||||
where: { username },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) error = "That username is already taken";
|
||||
await sendVerification(created.id, mail);
|
||||
} catch {
|
||||
error = "Registration is temporarily unavailable";
|
||||
// No-op: account is created; user can request a new link later.
|
||||
}
|
||||
} catch {
|
||||
return "Could not create the account (is the username unique?)";
|
||||
}
|
||||
|
||||
if (!error) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
try {
|
||||
const created = await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
password: await hashPassword(password),
|
||||
mail,
|
||||
accountCreated: now,
|
||||
ipRegister: ip,
|
||||
ipCurrent: ip,
|
||||
look: DEFAULT_LOOK,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
// Fire the verification email. Best-effort: a mail/SMTP failure must not
|
||||
// abort a successful registration, so swallow its errors here.
|
||||
try {
|
||||
await sendVerification(created.id, mail);
|
||||
} catch {
|
||||
// No-op: account is created; user can request a new link later.
|
||||
}
|
||||
} catch {
|
||||
error = "Could not create the account (is the username unique?)";
|
||||
}
|
||||
}
|
||||
|
||||
// redirect() throws NEXT_REDIRECT — must be OUTSIDE any try/catch.
|
||||
if (error) redirect(`/register?error=${encodeURIComponent(error)}`);
|
||||
redirect("/login?registered=1");
|
||||
}
|
||||
+50
-31
@@ -2,6 +2,7 @@
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { LaravelEncrypter } from "@/lib/auth/laravel-encrypter";
|
||||
import { generateTotpSecret, verifyTotp } from "@/lib/auth/totp";
|
||||
import { auth } from "@/lib/auth";
|
||||
@@ -15,20 +16,64 @@ async function sessionUserId(): Promise<number> {
|
||||
return Number(session.user.id);
|
||||
}
|
||||
|
||||
/** Step 1: generate a secret, store it encrypted but UNconfirmed. */
|
||||
function generateRecoveryCodes(): string[] {
|
||||
const codes: string[] = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
codes.push(randomBytes(4).toString("hex").toUpperCase().replace(/(.{4})/, "$1-"));
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/** Verify a TOTP code OR a recovery code. Returns the updated recovery codes (minus used one) if a recovery code was used, or null on failure. */
|
||||
async function verifyTwoFactorCode(
|
||||
userId: number, code: string,
|
||||
): Promise<{ ok: boolean; updatedRecoveryCodes?: string | null }> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { twoFactorSecret: true, twoFactorRecoveryCodes: true },
|
||||
});
|
||||
if (!user?.twoFactorSecret) return { ok: false };
|
||||
|
||||
// Try TOTP first
|
||||
try {
|
||||
const secret = new LaravelEncrypter(env.APP_KEY as string).decrypt(user.twoFactorSecret);
|
||||
if (verifyTotp(code, secret)) return { ok: true };
|
||||
} catch { /* fall through to recovery */ }
|
||||
|
||||
// Try recovery codes
|
||||
if (user.twoFactorRecoveryCodes) {
|
||||
let codes: string[];
|
||||
try { codes = JSON.parse(user.twoFactorRecoveryCodes) as string[]; } catch { codes = []; }
|
||||
const idx = codes.indexOf(code);
|
||||
if (idx !== -1) {
|
||||
codes.splice(idx, 1);
|
||||
const remaining = codes.length > 0 ? JSON.stringify(codes) : null;
|
||||
return { ok: true, updatedRecoveryCodes: remaining };
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
/** Step 1: generate a secret and recovery codes, store encrypted but UNconfirmed. */
|
||||
export async function beginTwoFactor(): Promise<void> {
|
||||
const id = await sessionUserId();
|
||||
if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey");
|
||||
const secret = generateTotpSecret();
|
||||
const encrypted = new LaravelEncrypter(env.APP_KEY).encrypt(secret);
|
||||
const codes = generateRecoveryCodes();
|
||||
await prisma.user.update({
|
||||
where: { id },
|
||||
data: { twoFactorSecret: encrypted, twoFactorConfirmedAt: null },
|
||||
data: {
|
||||
twoFactorSecret: encrypted,
|
||||
twoFactorConfirmedAt: null,
|
||||
twoFactorRecoveryCodes: JSON.stringify(codes),
|
||||
},
|
||||
});
|
||||
revalidatePath("/settings/2fa");
|
||||
}
|
||||
|
||||
/** Step 2: verify a code against the pending secret, then confirm. */
|
||||
/** Step 2: verify a code against the pending secret, then confirm and show recovery codes. */
|
||||
export async function confirmTwoFactor(formData: FormData): Promise<void> {
|
||||
const id = await sessionUserId();
|
||||
if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey");
|
||||
@@ -37,20 +82,7 @@ export async function confirmTwoFactor(formData: FormData): Promise<void> {
|
||||
|
||||
const code = String(formData.get("code") ?? "").trim();
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { twoFactorSecret: true },
|
||||
});
|
||||
|
||||
let ok = false;
|
||||
if (user?.twoFactorSecret && code) {
|
||||
try {
|
||||
const secret = new LaravelEncrypter(env.APP_KEY).decrypt(user.twoFactorSecret);
|
||||
ok = verifyTotp(code, secret);
|
||||
} catch {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
const { ok } = await verifyTwoFactorCode(id, code);
|
||||
if (!ok) redirect("/settings/2fa?error=badcode");
|
||||
|
||||
await prisma.user.update({ where: { id }, data: { twoFactorConfirmedAt: new Date() } });
|
||||
@@ -65,20 +97,7 @@ export async function disableTwoFactor(formData: FormData): Promise<void> {
|
||||
|
||||
const code = String(formData.get("code") ?? "").trim();
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { twoFactorSecret: true },
|
||||
});
|
||||
|
||||
let ok = false;
|
||||
if (user?.twoFactorSecret && code) {
|
||||
try {
|
||||
const secret = new LaravelEncrypter(env.APP_KEY).decrypt(user.twoFactorSecret);
|
||||
ok = verifyTotp(code, secret);
|
||||
} catch {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
const { ok } = await verifyTwoFactorCode(id, code);
|
||||
if (!ok) redirect("/settings/2fa?error=badcode");
|
||||
|
||||
await prisma.user.update({
|
||||
|
||||
Reference in new issue
Block a user