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
@@ -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