Production hardening: error pages, rate limiting, metadata
- Custom not-found (404) + error / global-error boundaries, styled with
the public design system; raw errors logged, never shown to users.
- In-process rate limiter (src/lib/rate-limit.ts) wired into the abuse-
prone flows: login (10/5min/IP), register (5/10min/IP), password-reset
request (3/15min/IP), keyed by the proxy-forwarded client IP.
- SEO/metadata: root generateMetadata sets a `%s · {hotel}` title
template from the live hotel_name; dynamic generateMetadata on
news/[slug] (article title + excerpt) and u/[username] (name + motto);
static titles on 12 primary public pages.
- env.ts: added the vars introduced since (PASSWORD_HASH, OPENAI_API_KEY,
DISCORD_WEBHOOK_URL, ALERT_EMAIL, PAYPAL_*) so env stays authoritative.
Verified on the prod server: /missing → 404 card, news title renders
"News · Habbo". tsc 0, vitest 49/49, next build 0.
This commit is contained in:
1 parent
e9ea19795a
commit
6f15e0c8a3
23 files changed
+276
-5
No files matched your search
@@ -3,6 +3,7 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { redirect } from "next/navigation";
|
||||
import { hashPassword } from "@/lib/auth/password";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendMail } from "@/lib/services/email";
|
||||
import { env } from "@/env";
|
||||
@@ -16,8 +17,11 @@ function sha256(s: string): string {
|
||||
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;
|
||||
|
||||
// Always respond the same way so we don't reveal which emails exist.
|
||||
if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
||||
if (allowed && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
||||
try {
|
||||
const user = await prisma.user.findFirst({ where: { mail: email }, select: { id: true } });
|
||||
if (user) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { redirect } from "next/navigation";
|
||||
import { sendVerification } from "@/actions/email-verify";
|
||||
import { hashPassword } from "@/lib/auth/password";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const USERNAME_RE = /^[A-Za-z0-9_\-=?!@:.,]{3,25}$/;
|
||||
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
||||
@@ -21,6 +22,12 @@ export async function register(formData: FormData): Promise<void> {
|
||||
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) {
|
||||
const limit = rateLimit(`register:${await clientIp()}`, 5, 10 * 60_000);
|
||||
if (!limit.ok) error = "Too many sign-up attempts. Please wait a few minutes and try again.";
|
||||
}
|
||||
|
||||
// Uniqueness check (kept out of the success path's try so NEXT_REDIRECT propagates).
|
||||
if (!error) {
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Badges" };
|
||||
|
||||
// Canonical Habbo badge image CDN. A badge_key (e.g. "ADM") maps to a .gif here.
|
||||
const BADGE_IMG_BASE = "https://images.habbo.com/c_images/album1584";
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import { ContentCard } from "@/components/public/ui";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Community" };
|
||||
|
||||
const LINKS = [
|
||||
{
|
||||
href: "/rankings",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Route-segment error boundary. Renders inside the root layout (so the shell
|
||||
* stays), shows a friendly card, and offers a reset. The raw error is logged to
|
||||
* the console, never shown to the user.
|
||||
*/
|
||||
export default function Error({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<div className="content-card">
|
||||
<div className="content-card-head">
|
||||
<span className="content-card-icon" aria-hidden>
|
||||
⚠️
|
||||
</span>
|
||||
<div className="content-card-head-text">
|
||||
<p className="content-card-title">Something went wrong</p>
|
||||
<p className="content-card-subtitle">An unexpected error occurred</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="content-card-body">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
Try again — if the problem persists, please contact a member of staff.
|
||||
</p>
|
||||
<div style={{ display: "flex", gap: "0.6rem", flexWrap: "wrap" }}>
|
||||
<button type="button" className="btn btn-primary" onClick={() => reset()}>
|
||||
Try again
|
||||
</button>
|
||||
<a className="btn btn-outline" href="/">
|
||||
Back home
|
||||
</a>
|
||||
</div>
|
||||
{error.digest ? (
|
||||
<p className="muted" style={{ marginTop: "0.75rem", fontSize: "0.75rem" }}>
|
||||
Reference: {error.digest}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Friends" };
|
||||
|
||||
export default async function FriendsPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Last-resort boundary for errors thrown in the root layout itself. It replaces
|
||||
* the whole document, so it must render its own <html>/<body> and can't rely on
|
||||
* the app shell or its CSS variables.
|
||||
*/
|
||||
export default function GlobalError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
style={{
|
||||
margin: 0,
|
||||
minHeight: "100vh",
|
||||
display: "grid",
|
||||
placeItems: "center",
|
||||
fontFamily: "Nunito, system-ui, sans-serif",
|
||||
background: "#0f1117",
|
||||
color: "#e5e7eb",
|
||||
}}
|
||||
>
|
||||
<div style={{ textAlign: "center", padding: "2rem", maxWidth: 420 }}>
|
||||
<div style={{ fontSize: "2.5rem" }}>⚠️</div>
|
||||
<h1 style={{ margin: "0.5rem 0", fontSize: "1.4rem" }}>Something went wrong</h1>
|
||||
<p style={{ color: "#9ca3af", marginTop: 0 }}>
|
||||
The hotel ran into an unexpected error. Please try again.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => reset()}
|
||||
style={{
|
||||
marginTop: "1rem",
|
||||
padding: "0.55rem 1.4rem",
|
||||
border: "none",
|
||||
borderRadius: 10,
|
||||
fontWeight: 700,
|
||||
cursor: "pointer",
|
||||
background: "#f59e0b",
|
||||
color: "#1a1a2e",
|
||||
}}
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Guilds" };
|
||||
|
||||
type GuildCard = {
|
||||
id: number;
|
||||
name: string;
|
||||
|
||||
+8
-4
@@ -9,6 +9,7 @@ import { SiteHeader } from "@/components/site-header";
|
||||
import { ThemeVars } from "@/components/theme-vars";
|
||||
import { TopHeader } from "@/components/top-header";
|
||||
import { enforceSiteAccess } from "@/lib/access-guard";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
import "./globals.css";
|
||||
|
||||
const nunito = Nunito({
|
||||
@@ -18,10 +19,13 @@ const nunito = Nunito({
|
||||
variable: "--font-nunito",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "AtomCMS",
|
||||
description: "AtomCMS — retro hotel CMS (Next.js conversion)",
|
||||
};
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const hotel = (await siteSettings.get("hotel_name", "Atom")) ?? "Atom";
|
||||
return {
|
||||
title: { default: hotel, template: `%s · ${hotel}` },
|
||||
description: `${hotel} — a Habbo retro hotel. Hang out, collect furni and meet friends.`,
|
||||
};
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: ReactNode }) {
|
||||
await enforceSiteAccess();
|
||||
|
||||
@@ -6,6 +6,8 @@ import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Leaderboard" };
|
||||
|
||||
// AtomCMS-faithful currency type ids (see prisma/schema.prisma UsersCurrency):
|
||||
// Credits = -1 (lives on users.credits), Duckets = 0, Diamonds = 5.
|
||||
const TABS = [
|
||||
|
||||
@@ -3,6 +3,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Marketplace" };
|
||||
|
||||
// state == 1 → an active, unsold offer in the Arcturus marketplace.
|
||||
const STATE_ACTIVE = 1;
|
||||
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { excerpt } from "@/lib/format";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { postComment } from "@/actions/article-comments";
|
||||
import { toggleReaction } from "@/actions/article-reactions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
}): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const article = await prisma.websiteArticles
|
||||
.findUnique({ where: { slug }, select: { title: true, shortStory: true } })
|
||||
.catch(() => null);
|
||||
if (!article) return { title: "Article" };
|
||||
return { title: article.title, description: excerpt(article.shortStory, 160) };
|
||||
}
|
||||
|
||||
// The reaction set offered by the voting UI. Must stay in sync with
|
||||
// ALLOWED_REACTIONS in src/actions/article-reactions.ts.
|
||||
const REACTIONS: { key: string; label: string }[] = [
|
||||
|
||||
@@ -5,6 +5,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "News" };
|
||||
|
||||
function formatDate(d: Date | null): string {
|
||||
return d ? d.toISOString().slice(0, 10) : "";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import Link from "next/link";
|
||||
import { ContentCard } from "@/components/public/ui";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<main style={{ display: "grid", gap: "1.5rem" }}>
|
||||
<ContentCard icon="🧭" title="Page not found" subtitle="Error 404">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
The page you’re looking for doesn’t exist or has moved.
|
||||
</p>
|
||||
<div style={{ display: "flex", gap: "0.6rem", flexWrap: "wrap" }}>
|
||||
<Link className="btn btn-primary" href="/">
|
||||
Back home
|
||||
</Link>
|
||||
<Link className="btn btn-outline" href="/news">
|
||||
Latest news
|
||||
</Link>
|
||||
</div>
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Photos" };
|
||||
|
||||
type Photo = {
|
||||
id: number;
|
||||
userId: number;
|
||||
|
||||
@@ -6,6 +6,8 @@ import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Rankings" };
|
||||
|
||||
type TopUser = {
|
||||
username: string;
|
||||
look: string;
|
||||
|
||||
@@ -5,6 +5,8 @@ import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Rare values" };
|
||||
|
||||
type CategoryRow = {
|
||||
id: bigint;
|
||||
name: string;
|
||||
|
||||
@@ -5,6 +5,8 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Shop" };
|
||||
|
||||
// Faithful to AtomCMS WebsiteShopArticle::price(): costs are stored in cents,
|
||||
// the displayed price is costs/100 with a floor of 1.
|
||||
function priceLabel(costs: number): string {
|
||||
|
||||
@@ -5,6 +5,8 @@ import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const metadata = { title: "Staff" };
|
||||
|
||||
type StaffMember = {
|
||||
username: string;
|
||||
look: string;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ContentCard, EmptyState, OnlineBadge, StatBlock } from "@/components/public/ui";
|
||||
import { auth } from "@/lib/auth";
|
||||
@@ -8,6 +9,19 @@ import { postGuestbook } from "@/actions/guestbook";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ username: string }>;
|
||||
}): Promise<Metadata> {
|
||||
const { username } = await params;
|
||||
const user = await prisma.user
|
||||
.findUnique({ where: { username }, select: { username: true, motto: true } })
|
||||
.catch(() => null);
|
||||
if (!user) return { title: "Profile" };
|
||||
return { title: user.username, description: user.motto || `${user.username}'s profile` };
|
||||
}
|
||||
|
||||
// Canonical Habbo badge image CDN. Badge codes (e.g. "ADM") map to a .gif here.
|
||||
const BADGE_IMG_BASE = "https://images.habbo.com/c_images/album1584";
|
||||
|
||||
|
||||
+11
@@ -40,6 +40,17 @@ const schema = z.object({
|
||||
.string()
|
||||
.optional()
|
||||
.transform((v) => v === "true" || v === "1"),
|
||||
// Hashing driver for NEW passwords: bcrypt (default, fits varchar(64)) | argon2id.
|
||||
PASSWORD_HASH: z.enum(["bcrypt", "argon2id"]).optional(),
|
||||
// Optional AI content moderation (comments / guestbook).
|
||||
OPENAI_API_KEY: z.string().optional(),
|
||||
// Optional alerting (jobs worker / alert service).
|
||||
DISCORD_WEBHOOK_URL: z.string().url().optional(),
|
||||
ALERT_EMAIL: z.string().optional(),
|
||||
// Optional PayPal top-up.
|
||||
PAYPAL_CLIENT_ID: z.string().optional(),
|
||||
PAYPAL_SECRET: z.string().optional(),
|
||||
PAYPAL_API: z.string().url().optional(),
|
||||
});
|
||||
|
||||
type Env = z.infer<typeof schema>;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LaravelEncrypter } from "@/lib/auth/laravel-encrypter";
|
||||
import { checkLogin } from "@/lib/auth/password";
|
||||
import { verifyTotp } from "@/lib/auth/totp";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
import { env } from "@/env";
|
||||
|
||||
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
@@ -24,6 +25,9 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
const password = String(credentials?.password ?? "");
|
||||
if (!username || !password) return null;
|
||||
|
||||
// Throttle login attempts per IP (10 per 5 min) against credential stuffing.
|
||||
if (!rateLimit(`login:${await clientIp()}`, 10, 5 * 60_000).ok) return null;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { username } });
|
||||
if (!user) return null;
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { headers } from "next/headers";
|
||||
|
||||
/**
|
||||
* Tiny in-process fixed-window rate limiter for abuse-prone server actions
|
||||
* (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}`.
|
||||
*/
|
||||
type Bucket = { count: number; resetAt: number };
|
||||
const buckets = new Map<string, Bucket>();
|
||||
|
||||
export interface RateLimitResult {
|
||||
ok: boolean;
|
||||
/** Seconds until the window resets (0 when allowed). */
|
||||
retryAfter: number;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
const bucket = buckets.get(key);
|
||||
if (!bucket || now >= bucket.resetAt) {
|
||||
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
||||
return { ok: true, retryAfter: 0 };
|
||||
}
|
||||
if (bucket.count >= limit) {
|
||||
return { ok: false, retryAfter: Math.max(1, Math.ceil((bucket.resetAt - now) / 1000)) };
|
||||
}
|
||||
bucket.count += 1;
|
||||
return { ok: true, retryAfter: 0 };
|
||||
}
|
||||
|
||||
/** Best-effort client IP from the proxy headers our edge proxy forwards. */
|
||||
export async function clientIp(): Promise<string> {
|
||||
try {
|
||||
const h = await headers();
|
||||
return (
|
||||
h.get("x-real-client-ip") ??
|
||||
h.get("cf-connecting-ip") ??
|
||||
h.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||
h.get("x-real-ip") ??
|
||||
"0.0.0.0"
|
||||
);
|
||||
} catch {
|
||||
return "0.0.0.0";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user