diff --git a/src/actions/password-reset.ts b/src/actions/password-reset.ts index c6985db7..495b56c7 100644 --- a/src/actions/password-reset.ts +++ b/src/actions/password-reset.ts @@ -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 { 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) { diff --git a/src/actions/register.ts b/src/actions/register.ts index 7a756fc8..bccf4e29 100644 --- a/src/actions/register.ts +++ b/src/actions/register.ts @@ -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 { 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 { diff --git a/src/app/badges/page.tsx b/src/app/badges/page.tsx index 1fa3dca8..8710f0e1 100644 --- a/src/app/badges/page.tsx +++ b/src/app/badges/page.tsx @@ -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"; diff --git a/src/app/community/page.tsx b/src/app/community/page.tsx index e8251a70..f705c5b3 100644 --- a/src/app/community/page.tsx +++ b/src/app/community/page.tsx @@ -3,6 +3,8 @@ import { ContentCard } from "@/components/public/ui"; export const dynamic = "force-dynamic"; +export const metadata = { title: "Community" }; + const LINKS = [ { href: "/rankings", diff --git a/src/app/error.tsx b/src/app/error.tsx new file mode 100644 index 00000000..b7966727 --- /dev/null +++ b/src/app/error.tsx @@ -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 ( +
+
+
+ + ⚠️ + +
+

Something went wrong

+

An unexpected error occurred

+
+
+
+

+ Try again — if the problem persists, please contact a member of staff. +

+
+ + + Back home + +
+ {error.digest ? ( +

+ Reference: {error.digest} +

+ ) : null} +
+
+
+ ); +} diff --git a/src/app/friends/page.tsx b/src/app/friends/page.tsx index 286fbf89..3b90b017 100644 --- a/src/app/friends/page.tsx +++ b/src/app/friends/page.tsx @@ -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"); diff --git a/src/app/global-error.tsx b/src/app/global-error.tsx new file mode 100644 index 00000000..6cdbeded --- /dev/null +++ b/src/app/global-error.tsx @@ -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 / 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 ( + + +
+
⚠️
+

Something went wrong

+

+ The hotel ran into an unexpected error. Please try again. +

+ +
+ + + ); +} diff --git a/src/app/guilds/page.tsx b/src/app/guilds/page.tsx index c9e8567a..8aa5ae6f 100644 --- a/src/app/guilds/page.tsx +++ b/src/app/guilds/page.tsx @@ -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; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 1573265a..65218b08 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -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 { + 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(); diff --git a/src/app/leaderboard/page.tsx b/src/app/leaderboard/page.tsx index 7d3ab5f4..5539b213 100644 --- a/src/app/leaderboard/page.tsx +++ b/src/app/leaderboard/page.tsx @@ -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 = [ diff --git a/src/app/marketplace/page.tsx b/src/app/marketplace/page.tsx index 31c309b5..6a645062 100644 --- a/src/app/marketplace/page.tsx +++ b/src/app/marketplace/page.tsx @@ -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; diff --git a/src/app/news/[slug]/page.tsx b/src/app/news/[slug]/page.tsx index 4e1a446c..56687184 100644 --- a/src/app/news/[slug]/page.tsx +++ b/src/app/news/[slug]/page.tsx @@ -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 { + 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 }[] = [ diff --git a/src/app/news/page.tsx b/src/app/news/page.tsx index f3605e0e..b9121c22 100644 --- a/src/app/news/page.tsx +++ b/src/app/news/page.tsx @@ -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) : ""; } diff --git a/src/app/not-found.tsx b/src/app/not-found.tsx new file mode 100644 index 00000000..4c25a5c6 --- /dev/null +++ b/src/app/not-found.tsx @@ -0,0 +1,22 @@ +import Link from "next/link"; +import { ContentCard } from "@/components/public/ui"; + +export default function NotFound() { + return ( +
+ +

+ The page you’re looking for doesn’t exist or has moved. +

+
+ + Back home + + + Latest news + +
+
+
+ ); +} diff --git a/src/app/photos/page.tsx b/src/app/photos/page.tsx index ef6157a1..dd116d98 100644 --- a/src/app/photos/page.tsx +++ b/src/app/photos/page.tsx @@ -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; diff --git a/src/app/rankings/page.tsx b/src/app/rankings/page.tsx index 76444cd5..1ee6bc42 100644 --- a/src/app/rankings/page.tsx +++ b/src/app/rankings/page.tsx @@ -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; diff --git a/src/app/rares/page.tsx b/src/app/rares/page.tsx index 499e6b36..b3ca9e27 100644 --- a/src/app/rares/page.tsx +++ b/src/app/rares/page.tsx @@ -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; diff --git a/src/app/shop/page.tsx b/src/app/shop/page.tsx index ed067ccc..e8783506 100644 --- a/src/app/shop/page.tsx +++ b/src/app/shop/page.tsx @@ -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 { diff --git a/src/app/staff/page.tsx b/src/app/staff/page.tsx index 2267d767..01b7914c 100644 --- a/src/app/staff/page.tsx +++ b/src/app/staff/page.tsx @@ -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; diff --git a/src/app/u/[username]/page.tsx b/src/app/u/[username]/page.tsx index 3c60e029..40bfd4c4 100644 --- a/src/app/u/[username]/page.tsx +++ b/src/app/u/[username]/page.tsx @@ -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 { + 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"; diff --git a/src/env.ts b/src/env.ts index d5205c84..f9c930dd 100644 --- a/src/env.ts +++ b/src/env.ts @@ -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; diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 7955c8dd..6a837d70 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -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; diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts new file mode 100644 index 00000000..2aed43d8 --- /dev/null +++ b/src/lib/rate-limit.ts @@ -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(); + +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 { + 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"; + } +}