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
+38
-1
@@ -1,17 +1,54 @@
|
||||
import type { NextConfig } from "next";
|
||||
import createNextIntlPlugin from "next-intl/plugin";
|
||||
|
||||
const securityHeaders = [
|
||||
{ key: "X-DNS-Prefetch-Control", value: "on" },
|
||||
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{
|
||||
key: "Permissions-Policy",
|
||||
value: "camera=(), microphone=(), geolocation=(), interest-cohort=()",
|
||||
},
|
||||
{
|
||||
key: "Content-Security-Policy",
|
||||
value: [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-eval' 'unsafe-inline' https://challenges.cloudflare.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob: https:",
|
||||
"frame-src 'self' https://challenges.cloudflare.com https://www.google.com/recaptcha/",
|
||||
"connect-src 'self' https: wss:",
|
||||
"font-src 'self' data:",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
].join("; "),
|
||||
},
|
||||
];
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// This app lives inside the Laravel repo tree (which has its own lockfiles);
|
||||
// pin the Turbopack root so Next doesn't infer a parent directory.
|
||||
turbopack: { root: import.meta.dirname },
|
||||
|
||||
// Prisma + the MariaDB driver adapter are native/server-only — keep them out
|
||||
// of the bundle (same approach as the habbo-next reference).
|
||||
serverExternalPackages: ["@prisma/adapter-mariadb", "mariadb", "@prisma/client"],
|
||||
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: securityHeaders,
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
// next-intl WITHOUT i18n routing — locale comes from the NEXT_LOCALE cookie via
|
||||
// src/i18n/request.ts, so URLs and the access-guard middleware stay unchanged.
|
||||
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
|
||||
|
||||
export default withNextIntl(nextConfig);
|
||||
export default withNextIntl(nextConfig);
|
||||
@@ -35,7 +35,7 @@ model User {
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique(map: "username") @db.VarChar(25)
|
||||
realName String @default("KREWS DEV") @map("real_name") @db.VarChar(25)
|
||||
password String @db.VarChar(64)
|
||||
password String @db.VarChar(255)
|
||||
mail String? @db.VarChar(500)
|
||||
mailVerified String @default("0") @map("mail_verified")
|
||||
accountCreated Int @map("account_created")
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
@@ -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
File diff suppressed because it is too large.
Load diff
+50
-31
File diff suppressed because it is too large.
Load diff
@@ -23,11 +23,11 @@ export default async function TwoFactorPage({
|
||||
const sp = await searchParams;
|
||||
const id = Number(session.user.id);
|
||||
|
||||
let user: { twoFactorSecret: string | null; twoFactorConfirmedAt: Date | null } | null = null;
|
||||
let user: { twoFactorSecret: string | null; twoFactorConfirmedAt: Date | null; twoFactorRecoveryCodes: string | null } | null = null;
|
||||
try {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { twoFactorSecret: true, twoFactorConfirmedAt: true },
|
||||
select: { twoFactorSecret: true, twoFactorConfirmedAt: true, twoFactorRecoveryCodes: true },
|
||||
});
|
||||
} catch {
|
||||
user = null;
|
||||
@@ -40,10 +40,14 @@ export default async function TwoFactorPage({
|
||||
|
||||
let secret = "";
|
||||
let uri = "";
|
||||
let recoveryCodes: string[] = [];
|
||||
if (pending && hasAppKey && user?.twoFactorSecret) {
|
||||
try {
|
||||
secret = new LaravelEncrypter(env.APP_KEY as string).decrypt(user.twoFactorSecret);
|
||||
uri = totpKeyUri(secret, session.user.name ?? "user", hotelName);
|
||||
if (user.twoFactorRecoveryCodes) {
|
||||
recoveryCodes = JSON.parse(user.twoFactorRecoveryCodes) as string[];
|
||||
}
|
||||
} catch {
|
||||
secret = "";
|
||||
}
|
||||
@@ -61,7 +65,40 @@ export default async function TwoFactorPage({
|
||||
subtitle={t("subtitle")}
|
||||
>
|
||||
{sp.enabled ? (
|
||||
<p style={{ color: "var(--color-accent)", marginTop: 0 }}>{t("nowEnabled")}</p>
|
||||
<>
|
||||
<p style={{ color: "var(--color-accent)", marginTop: 0 }}>{t("nowEnabled")}</p>
|
||||
<div style={{
|
||||
background: "var(--color-surface)",
|
||||
border: "1px solid var(--color-border)",
|
||||
borderRadius: 8,
|
||||
padding: "1rem",
|
||||
marginTop: "0.5rem",
|
||||
}}>
|
||||
<h4 style={{ margin: "0 0 0.5rem" }}>Recovery Codes</h4>
|
||||
<p className="muted" style={{ fontSize: "0.85rem", margin: "0 0 0.75rem" }}>
|
||||
Store these one-time use codes in a safe place. Each can be used once
|
||||
if you lose access to your authenticator app.
|
||||
</p>
|
||||
<div style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "1fr 1fr",
|
||||
gap: "0.25rem",
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.9rem",
|
||||
}}>
|
||||
{recoveryCodes.map((code) => (
|
||||
<code key={code} style={{
|
||||
userSelect: "all",
|
||||
padding: "0.25rem 0.5rem",
|
||||
background: "var(--color-background)",
|
||||
borderRadius: 4,
|
||||
}}>
|
||||
{code}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
{sp.disabled ? (
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+14
-1
@@ -29,7 +29,20 @@ const schema = z.object({
|
||||
// NextAuth v5 reads AUTH_SECRET itself; declared here for documentation/typing.
|
||||
AUTH_SECRET: z.string().min(1).optional(),
|
||||
// Laravel APP_KEY (base64:...) — needed to read existing 2FA secrets.
|
||||
APP_KEY: z.string().optional(),
|
||||
APP_KEY: z.string().optional().refine(
|
||||
(v) => {
|
||||
if (!v) return true;
|
||||
if (v.startsWith("base64:")) {
|
||||
try {
|
||||
const decoded = atob(v.slice(7));
|
||||
// Catch the known placeholder key
|
||||
if (decoded.includes("placeholder")) return false;
|
||||
} catch { return false; }
|
||||
}
|
||||
return v.length >= 16;
|
||||
},
|
||||
{ message: "APP_KEY is a placeholder or invalid — generate a real 32-byte key: echo 'base64:'$(openssl rand -base64 32)" },
|
||||
),
|
||||
// Optional OAuth providers (enabled only when both id+secret are set).
|
||||
DISCORD_CLIENT_ID: z.string().optional(),
|
||||
DISCORD_CLIENT_SECRET: z.string().optional(),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { redirect } from "next/navigation";
|
||||
import { isStaff } from "@/lib/admin/is-staff";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
export { isStaff };
|
||||
|
||||
@@ -31,3 +32,14 @@ export async function requireStaff(): Promise<StaffUser> {
|
||||
username: session.user.name ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Like requireStaff but also rate-limits the action per staff user (30 requests
|
||||
* per minute). Use on sensitive admin actions (ban, rank-change, settings edit).
|
||||
*/
|
||||
export async function requireStaffRateLimited(): Promise<StaffUser> {
|
||||
const staff = await requireStaff();
|
||||
const ip = await clientIp();
|
||||
if (!rateLimit(`admin:${staff.id}:${ip}`, 30, 60_000).ok) redirect("/admin?error=ratelimit");
|
||||
return staff;
|
||||
}
|
||||
+5
-4
@@ -2,17 +2,18 @@ import { NextResponse } from "next/server";
|
||||
|
||||
/**
|
||||
* JSON response helper for the public REST API. Serialises BigInt (Prisma ids)
|
||||
* to strings — JSON.stringify throws on BigInt otherwise — and sets permissive
|
||||
* CORS so the game client / external integrations can read it (mirrors the
|
||||
* AtomCMS API CORS config).
|
||||
* to strings — JSON.stringify throws on BigInt otherwise — and sets CORS to
|
||||
* APP_URL so the game client / external integrations can read it.
|
||||
*/
|
||||
const CORS_ORIGIN = process.env.APP_URL ?? "http://localhost:3000";
|
||||
|
||||
export function apiJson(data: unknown, init?: ResponseInit): NextResponse {
|
||||
const body = JSON.stringify(data, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
|
||||
return new NextResponse(body, {
|
||||
status: init?.status ?? 200,
|
||||
headers: {
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-allow-origin": CORS_ORIGIN,
|
||||
"cache-control": "no-store",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
|
||||
+35
-9
@@ -9,8 +9,40 @@ import { prisma } from "@/lib/prisma";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
import { env } from "@/env";
|
||||
|
||||
async function verify2faCode(userId: number, code: string): Promise<boolean> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { twoFactorSecret: true, twoFactorRecoveryCodes: true },
|
||||
});
|
||||
if (!user?.twoFactorSecret) return false;
|
||||
|
||||
// Try TOTP first
|
||||
try {
|
||||
const secret = new LaravelEncrypter(env.APP_KEY!).decrypt(user.twoFactorSecret);
|
||||
if (verifyTotp(code, secret)) return true;
|
||||
} catch { /* fall through to recovery */ }
|
||||
|
||||
// Try recovery codes
|
||||
if (user.twoFactorRecoveryCodes) {
|
||||
let codes: string[];
|
||||
try { codes = JSON.parse(user.twoFactorRecoveryCodes) as string[]; } catch { return false; }
|
||||
const idx = codes.indexOf(code);
|
||||
if (idx !== -1) {
|
||||
codes.splice(idx, 1);
|
||||
const remaining = codes.length > 0 ? JSON.stringify(codes) : null;
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { twoFactorRecoveryCodes: remaining },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
trustHost: true,
|
||||
trustHost: process.env.NODE_ENV === "development",
|
||||
session: { strategy: "jwt", maxAge: 24 * 60 * 60 },
|
||||
pages: { signIn: "/login" },
|
||||
providers: [
|
||||
@@ -52,17 +84,11 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
});
|
||||
}
|
||||
|
||||
// Two-factor: if enabled, a valid TOTP code is required. The secret is
|
||||
// Laravel-encrypted with APP_KEY (fail closed if it cannot be read).
|
||||
// Two-factor: if enabled, a valid TOTP or recovery code is required.
|
||||
if (user.twoFactorConfirmedAt && user.twoFactorSecret) {
|
||||
const code = String(credentials?.code ?? "").trim();
|
||||
if (!code || !env.APP_KEY) return null;
|
||||
try {
|
||||
const secret = new LaravelEncrypter(env.APP_KEY).decrypt(user.twoFactorSecret);
|
||||
if (!verifyTotp(code, secret)) return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!(await verify2faCode(user.id, code))) return null;
|
||||
}
|
||||
|
||||
// Record the successful login for the user's "session logs" page.
|
||||
|
||||
@@ -14,10 +14,8 @@ const ARGON2_PARAMS = {
|
||||
const BCRYPT_ROUNDS = 12;
|
||||
|
||||
// Which algorithm hashPassword() emits for NEW/upgraded passwords.
|
||||
// - "bcrypt" (DEFAULT): 60-char $2y$ hash. Fits a varchar(64) users.password
|
||||
// (the common emulator/AtomCMS column width) and matches existing accounts.
|
||||
// - "argon2id": ~97-char PHC hash. ONLY usable if users.password is widened
|
||||
// (e.g. varchar(255)). Opt in with PASSWORD_HASH=argon2id.
|
||||
// - "bcrypt" (DEFAULT): 60-char $2y$ hash. Fits varchar(255) users.password.
|
||||
// - "argon2id": ~97-char PHC hash. Opt in with PASSWORD_HASH=argon2id.
|
||||
// verifyPassword() always accepts BOTH, so logins keep working either way.
|
||||
function hashDriver(): "bcrypt" | "argon2id" {
|
||||
return process.env.PASSWORD_HASH?.toLowerCase() === "argon2id" ? "argon2id" : "bcrypt";
|
||||
|
||||
+25
-5
@@ -5,6 +5,8 @@ import { headers } from "next/headers";
|
||||
* (register, password reset, login). It's per-node (not shared across
|
||||
* instances) — fine for a single-server retro hotel; swap for Redis if you
|
||||
* ever scale out. Keys are typically `${action}:${ip}`.
|
||||
*
|
||||
* Periodic cleanup runs every 5 minutes to keep the map bounded.
|
||||
*/
|
||||
type Bucket = { count: number; resetAt: number };
|
||||
const buckets = new Map<string, Bucket>();
|
||||
@@ -15,13 +17,31 @@ export interface RateLimitResult {
|
||||
retryAfter: number;
|
||||
}
|
||||
|
||||
let lastCleanup = Date.now();
|
||||
const CLEANUP_INTERVAL_MS = 300_000; // 5 min
|
||||
const MAX_BUCKETS = 10_000;
|
||||
|
||||
function cleanup(): void {
|
||||
const now = Date.now();
|
||||
if (now - lastCleanup < CLEANUP_INTERVAL_MS) return;
|
||||
lastCleanup = now;
|
||||
if (buckets.size <= MAX_BUCKETS) {
|
||||
// Quick eviction of completely expired entries
|
||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
||||
} else {
|
||||
// Aggressive: clear all expired, then delete oldest 20% if still too large
|
||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
||||
if (buckets.size > MAX_BUCKETS) {
|
||||
const sorted = [...buckets.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt);
|
||||
const toRemove = Math.floor(sorted.length * 0.2);
|
||||
for (let i = 0; i < toRemove; i++) buckets.delete(sorted[i][0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
|
||||
const now = Date.now();
|
||||
|
||||
// Opportunistic cleanup so the map can't grow without bound.
|
||||
if (buckets.size > 5000) {
|
||||
for (const [k, b] of buckets) if (now >= b.resetAt) buckets.delete(k);
|
||||
}
|
||||
cleanup();
|
||||
|
||||
const bucket = buckets.get(key);
|
||||
if (!bucket || now >= bucket.resetAt) {
|
||||
|
||||
Reference in new issue
Block a user