perf: add bans.user_id index, Redis cache layer, rate-limit improvements, radio contest/giveaway columns, and tests
- Add DB index on bans.user_id to speed up per-request ban lookups (migration 0008) - Replace in-process rate limiter with Redis-backed implementation with in-memory fallback - Add Redis caching layer for site settings with TTL invalidation (migration 0009) - Add rate limiting to resetPassword to prevent token brute-force attacks - Update all rateLimit callers to await the now-async function - Flesh out RadioContests and RadioGiveaways models with title, description, prize, date, and winner columns - Update radio contest/giveaway pages to display new fields - Add tests for rate limiter (4 tests) and password-reset actions (3 tests) - Add REDIS_URL environment variable (optional, falls back to in-memory)
This commit is contained in:
1 parent
43c0ba6614
commit
5c638cd6bc
25 files changed
+449
-63
No files matched your search
@@ -19,7 +19,7 @@ export async function precheckLogin(
|
||||
const p = String(password ?? "");
|
||||
if (!u || !p) return "invalid";
|
||||
|
||||
if (!rateLimit(`precheck:${await clientIp()}`, 10, 5 * 60_000).ok) return "invalid";
|
||||
if (!(await rateLimit(`precheck:${await clientIp()}`, 10, 5 * 60_000)).ok) return "invalid";
|
||||
|
||||
let user: { password: string; twoFactorConfirmedAt: Date | null } | null = null;
|
||||
try {
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function createTicket(formData: FormData): Promise<void> {
|
||||
if (!Number.isInteger(userId) || userId <= 0) return;
|
||||
|
||||
const ip = await clientIp();
|
||||
if (!rateLimit(`ticket:${userId}`, 3, 60_000).ok) return;
|
||||
if (!(await rateLimit(`ticket:${userId}`, 3, 60_000)).ok) return;
|
||||
|
||||
const raw = {
|
||||
title: String(formData.get("title") ?? "").trim().slice(0, 255),
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { mockFindFirst, mockUpsert, mockFindUnique, mockUpdate, mockDelete, mockSendMail, mockRedirect } = vi.hoisted(
|
||||
() => ({
|
||||
mockFindFirst: vi.fn(),
|
||||
mockUpsert: vi.fn(),
|
||||
mockFindUnique: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
mockSendMail: vi.fn(),
|
||||
mockRedirect: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (...args: unknown[]) => {
|
||||
mockRedirect(...args);
|
||||
throw new Error("redirect");
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/prisma", () => ({
|
||||
prisma: {
|
||||
user: { findFirst: mockFindFirst, update: mockUpdate },
|
||||
passwordReset: { upsert: mockUpsert, findUnique: mockFindUnique, delete: mockDelete },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/services/email", () => ({
|
||||
sendMail: mockSendMail,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
rateLimit: vi.fn().mockResolvedValue({ ok: true, retryAfter: 0 }),
|
||||
clientIp: vi.fn().mockResolvedValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
vi.mock("@/env", () => ({
|
||||
env: { APP_URL: "http://localhost:3000", HOTEL_NAME: "TestHotel" },
|
||||
}));
|
||||
|
||||
import { requestReset } from "./password-reset";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("requestReset", () => {
|
||||
it("sends a reset email when the user exists", async () => {
|
||||
mockFindFirst.mockResolvedValue({ id: 1 });
|
||||
mockUpsert.mockResolvedValue({});
|
||||
|
||||
const fd = new FormData();
|
||||
fd.set("email", "[email protected]");
|
||||
|
||||
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
||||
|
||||
expect(mockFindFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { mail: "[email protected]" } }),
|
||||
);
|
||||
expect(mockUpsert).toHaveBeenCalled();
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
"[email protected]",
|
||||
expect.stringContaining("password reset"),
|
||||
expect.stringContaining("http://localhost:3000/reset"),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not send email when user is not found", async () => {
|
||||
mockFindFirst.mockResolvedValue(null);
|
||||
|
||||
const fd = new FormData();
|
||||
fd.set("email", "[email protected]");
|
||||
|
||||
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
||||
expect(mockSendMail).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate limits and does not throw on email without @", async () => {
|
||||
const fd = new FormData();
|
||||
fd.set("email", "not-an-email");
|
||||
|
||||
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
||||
expect(mockFindFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ export async function requestReset(formData: FormData): Promise<void> {
|
||||
const email = String(formData.get("email") ?? "").trim().toLowerCase();
|
||||
|
||||
// Throttle reset requests per IP (3 per 15 min) to curb email-bomb abuse.
|
||||
const allowed = rateLimit(`reset:${await clientIp()}`, 3, 15 * 60_000).ok;
|
||||
const allowed = (await rateLimit(`reset:${await clientIp()}`, 3, 15 * 60_000)).ok;
|
||||
|
||||
// Always respond the same way so we don't reveal which emails exist.
|
||||
if (allowed && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
||||
@@ -51,6 +51,11 @@ export async function resetPassword(formData: FormData): Promise<void> {
|
||||
const token = String(formData.get("token") ?? "").trim();
|
||||
const password = String(formData.get("password") ?? "");
|
||||
|
||||
// Throttle reset attempts per IP (5 per 15 min) to prevent token brute-force.
|
||||
if (!(await rateLimit(`resetpwd:${await clientIp()}`, 5, 15 * 60_000)).ok) {
|
||||
redirect(`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent("Too many attempts — try again later")}`);
|
||||
}
|
||||
|
||||
let error: string | null = null;
|
||||
if (password.length < 6) error = "Password must be at least 6 characters";
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ export async function postShout(formData: FormData): Promise<void> {
|
||||
if (!Number.isInteger(userId) || userId <= 0) return;
|
||||
|
||||
const ip = await clientIp();
|
||||
if (!rateLimit(`shout:${userId}`, 5, 30_000).ok) return;
|
||||
if (!(await rateLimit(`shout:${userId}`, 5, 30_000)).ok) return;
|
||||
|
||||
const raw = {
|
||||
message: String(formData.get("message") ?? "").trim().slice(0, 255),
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function register(prevState: string | null, formData: FormData): Pr
|
||||
const ip = await clientIp();
|
||||
|
||||
// Throttle sign-ups per IP (5 per 10 minutes) to curb account spam.
|
||||
if (!rateLimit(`register:${ip}`, 5, 10 * 60_000).ok) {
|
||||
if (!(await rateLimit(`register:${ip}`, 5, 10 * 60_000)).ok) {
|
||||
return "Too many sign-up attempts. Please wait a few minutes and try again.";
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ export async function confirmTwoFactor(formData: FormData): Promise<void> {
|
||||
const id = await sessionUserId();
|
||||
if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey");
|
||||
|
||||
if (!rateLimit(`2fa-confirm:${id}`, 5, 30_000).ok) redirect("/settings/2fa?error=ratelimit");
|
||||
if (!(await rateLimit(`2fa-confirm:${id}`, 5, 30_000)).ok) redirect("/settings/2fa?error=ratelimit");
|
||||
|
||||
const code = String(formData.get("code") ?? "").trim();
|
||||
|
||||
@@ -93,7 +93,7 @@ export async function disableTwoFactor(formData: FormData): Promise<void> {
|
||||
const id = await sessionUserId();
|
||||
if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey");
|
||||
|
||||
if (!rateLimit(`2fa-disable:${id}`, 5, 30_000).ok) redirect("/settings/2fa?error=ratelimit");
|
||||
if (!(await rateLimit(`2fa-disable:${id}`, 5, 30_000)).ok) redirect("/settings/2fa?error=ratelimit");
|
||||
|
||||
const code = String(formData.get("code") ?? "").trim();
|
||||
|
||||
|
||||
Reference in new issue
Block a user