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
+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");
|
||||
}
|
||||
Reference in new issue
Block a user