diff --git a/drizzle/migrations/0034_acl_midrank_revoke.sql b/drizzle/migrations/0034_acl_midrank_revoke.sql new file mode 100644 index 00000000..324f65f0 --- /dev/null +++ b/drizzle/migrations/0034_acl_midrank_revoke.sql @@ -0,0 +1,25 @@ +-- Repair the escalation introduced by 0018's rule 1 ("has admin.dashboard gets +-- ALL admin.*"). Migrating 0011 grants admin.dashboard to every rank >= 6 so +-- that the sidebar opens, which meant rank 6 silently acquired +-- admin.permissions.manage, admin.rcon.execute, admin.settings.edit, +-- admin.users.edit, admin.users.reset_password, admin.room.delete, ... +-- +-- Rule 1 is narrowed to `admin.%.view` (read-only, all the sidebar needs) in +-- both the migration set and the runtime repair action. This migration undoes +-- the over-grant on databases that already ran 0018: every role below the top +-- rank keeps dashboard + *.view and loses every other admin.* grant. Ranks +-- that legitimately hold tools keep them, because rule 3 only targets +-- rank >= 7 and those roles are not touched here. + +DELETE `amp` +FROM `acl_model_permissions` `amp` +JOIN `acl_roles` `ar` + ON `ar`.`id` = `amp`.`model_id` + AND `ar`.`model_type` = 'Role' + AND `amp`.`model_type` = 'Role' +JOIN `acl_permissions` `ap` + ON `ap`.`id` = `amp`.`permission_id` +WHERE `ap`.`slug` LIKE 'admin.%' + AND `ap`.`slug` NOT LIKE '%.view' + AND `ar`.`slug` REGEXP '^rank_[0-9]+$' + AND CAST(SUBSTRING(`ar`.`slug`, 7) AS UNSIGNED) < 7; diff --git a/src/actions/admin-media.ts b/src/actions/admin-media.ts index 02962c26..a050100e 100644 --- a/src/actions/admin-media.ts +++ b/src/actions/admin-media.ts @@ -4,11 +4,32 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { revalidatePath } from "next/cache"; import { requirePermission } from "@/lib/admin/guard"; +import { validateSiteImageUpload } from "@/lib/images/site-image-upload"; import { MEDIA_ROOT, resolveMediaPath } from "@/lib/media-storage"; import { PERMS } from "@/lib/permissions"; -const MAX_SIZE = 5 * 1024 * 1024; // 5MB -const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp"]; +/** + * Store an uploaded media file under MEDIA_ROOT. + * + * The extension always comes from the *detected* format (magic bytes + a full + * sharp decode), never from `file.name` or the browser-supplied MIME type: + * trusting either lets arbitrary bytes land on disk with an attacker-chosen name + * that the media route would then serve. + */ +async function storeUploadedMedia( + file: File, +): Promise<{ ok: true; name: string } | { ok: false; error: string }> { + const validated = await validateSiteImageUpload(file); + if (!validated.success) return { ok: false, error: validated.error }; + const baseDir = MEDIA_ROOT; + await mkdir(baseDir, { recursive: true }); + const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${validated.extension}`; + const filePath = resolveMediaPath(name); + if (!filePath.startsWith(baseDir + path.sep)) + return { ok: false, error: "Invalid path" }; + await writeFile(filePath, validated.bytes); + return { ok: true, name }; +} export async function uploadMedia( formData: FormData, @@ -16,25 +37,9 @@ export async function uploadMedia( await requirePermission(PERMS.PAGES_EDIT); const file = formData.get("file") as File | null; if (!file || file.size === 0) return { ok: false, error: "No file provided" }; - if (file.size > MAX_SIZE) - return { ok: false, error: "File too large (max 5MB)" }; - if (!ALLOWED.includes(file.type)) - return { - ok: false, - error: "Invalid file type. Allowed: PNG, JPEG, GIF, WebP", - }; - const baseDir = MEDIA_ROOT; - // eslint-disable-next-line security/detect-non-literal-fs-filename - await mkdir(baseDir, { recursive: true }); - - const ext = file.name.split(".").pop() ?? "png"; - const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; - const bytes = await file.arrayBuffer(); - const filePath = resolveMediaPath(name); - if (!filePath.startsWith(baseDir + path.sep)) throw new Error("Invalid path"); - // eslint-disable-next-line security/detect-non-literal-fs-filename - await writeFile(filePath, Buffer.from(bytes)); + const stored = await storeUploadedMedia(file); + if (!stored.ok) return { ok: false, error: stored.error }; revalidatePath("/api/media"); revalidatePath("/admin/media"); @@ -45,6 +50,8 @@ export async function deleteMedia(name: string): Promise { await requirePermission(PERMS.PAGES_EDIT); const { unlink } = await import("node:fs/promises"); const baseDir = MEDIA_ROOT; + // A name that is not a bare file name never reaches the unlink. + if (name.includes("/") || name.includes("\\") || name.includes("..")) return; const filePath = resolveMediaPath(name); if (!filePath.startsWith(baseDir + path.sep)) return; try { @@ -62,22 +69,11 @@ export async function uploadMediaAndReturn( await requirePermission(PERMS.PAGES_EDIT); const file = formData.get("file") as File | null; if (!file || file.size === 0) return ""; - if (file.size > MAX_SIZE) return ""; - if (!ALLOWED.includes(file.type)) return ""; - const baseDir = MEDIA_ROOT; - // eslint-disable-next-line security/detect-non-literal-fs-filename - await mkdir(baseDir, { recursive: true }); - - const ext = file.name.split(".").pop() ?? "png"; - const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`; - const bytes = await file.arrayBuffer(); - const filePath = resolveMediaPath(name); - if (!filePath.startsWith(baseDir + path.sep)) return ""; - // eslint-disable-next-line security/detect-non-literal-fs-filename - await writeFile(filePath, Buffer.from(bytes)); + const stored = await storeUploadedMedia(file); + if (!stored.ok) return ""; revalidatePath("/api/media"); revalidatePath("/admin/media"); - return `/api/media/${name}`; + return `/api/media/${stored.name}`; } diff --git a/src/actions/admin-settings.ts b/src/actions/admin-settings.ts index 27a5396c..745c7381 100644 --- a/src/actions/admin-settings.ts +++ b/src/actions/admin-settings.ts @@ -14,10 +14,19 @@ import { import { PERMS } from "@/lib/permissions"; import { clearOfficialHabboFurnidataCache } from "@/lib/services/habbo-furnidata-cache"; import { clearBadgeCache } from "@/lib/services/habboassets"; +import { + isSecretSettingKey, + SECRET_PLACEHOLDER, +} from "@/lib/services/setting-secrets"; import { siteSettings } from "@/lib/services/site-settings"; const managedKeySet = new Set(MANAGED_SETTING_KEYS); +// Raw keys only the CMS core is allowed to own. Writing an arbitrary key from +// the generic "advanced key/value" form previously meant a staff member could +// overwrite `turnstile_secret`, `force_staff_2fa` or `min_staff_rank`. +const RAW_SETTING_KEY_RE = /^[a-z0-9][a-z0-9_.-]{0,127}$/; + function normalizeSettingValue(key: string, value: string): string { if (key === HABBO_GAMEDATA_HOTEL_SETTING_KEY) { return normalizeHabboGamedataHotel(value); @@ -71,11 +80,12 @@ export async function updateSetting(formData: FormData): Promise { const key = String(formData.get("key") ?? "") .normalize("NFC") .trim(); - const value = normalizeSettingValue( - key, - String(formData.get("value") ?? "").normalize("NFC"), - ); - if (!key) return; + const raw = String(formData.get("value") ?? "").normalize("NFC"); + if (!key || !RAW_SETTING_KEY_RE.test(key)) return; + // Blank on a secret means "keep what is stored", so the UI can render a + // placeholder without the risk of wiping the credential. + if (isSecretSettingKey(key) && raw === SECRET_PLACEHOLDER) return; + const value = isSecretSettingKey(key) ? raw : normalizeSettingValue(key, raw); await db .insert(WebsiteSetting) .values({ key, value }) @@ -90,7 +100,7 @@ export async function createSetting(formData: FormData): Promise { const key = String(formData.get("key") ?? "") .normalize("NFC") .trim() - .slice(0, 255); + .slice(0, 128); const value = normalizeSettingValue( key, String(formData.get("value") ?? "").normalize("NFC"), @@ -99,7 +109,17 @@ export async function createSetting(formData: FormData): Promise { .normalize("NFC") .trim() .slice(0, 255); - if (!key) return; + // Managed keys go through `saveManagedSettings`; anything else must be a + // clearly namespaced custom key, and lockout/security settings are never + // writable through the free-form form. + if (!key || !RAW_SETTING_KEY_RE.test(key)) return; + if ( + key === "force_staff_2fa" || + key === "min_staff_rank" || + key === "maintenance_enabled" + ) { + return; + } await db .insert(WebsiteSetting) .values({ key, value, comment: comment || null }) diff --git a/src/actions/bulk-users.test.ts b/src/actions/bulk-users.test.ts index 22f2124b..25946767 100644 --- a/src/actions/bulk-users.test.ts +++ b/src/actions/bulk-users.test.ts @@ -41,7 +41,11 @@ const { }); vi.mock("@/lib/admin/guard", () => ({ requirePermission: vi.fn() })); -vi.mock("@/lib/permissions", () => ({ PERMS: { USERS_EDIT: "users.edit" } })); +vi.mock("@/lib/permissions", () => ({ + PERMS: { USERS_EDIT: "users.edit" }, + // Staff (rank 7) may act on anyone below the hotel's top rank. + getHighestRank: vi.fn(() => Promise.resolve(10)), +})); vi.mock("@/lib/db", () => ({ db: { delete: vi.fn(() => ({ where: deleteWhere })), @@ -109,7 +113,10 @@ beforeEach(() => { onDuplicateKeyUpdate.mockResolvedValue([{ affectedRows: 1 }]); updateWhere.mockResolvedValue([{ affectedRows: 1 }]); selectLimit.mockResolvedValue([]); - selectWhereResolved.mockResolvedValue([]); + // Rank rows for the per-id rank guard: every target sits below staff rank 7. + selectWhereResolved.mockResolvedValue([{ rank: 1 }]); + // Max slot of existing badges (consumed by the badge loop, not the guard). + selectWhereResolved.mockResolvedValueOnce([{ rank: 1 }]); }); describe("bulkUnban", () => { diff --git a/src/actions/bulk-users.ts b/src/actions/bulk-users.ts index 1bd037fa..8fda80e6 100644 --- a/src/actions/bulk-users.ts +++ b/src/actions/bulk-users.ts @@ -1,6 +1,7 @@ "use server"; import { and, eq, inArray, max, sql } from "drizzle-orm"; +import { isDynamicSuperAdmin } from "@/lib/admin/authorization-policy"; import { requirePermission } from "@/lib/admin/guard"; import { Ban, @@ -11,18 +12,69 @@ import { UsersCurrency, UsersSettings, } from "@/lib/db"; -import { PERMS } from "@/lib/permissions"; +import { getHighestRank, PERMS } from "@/lib/permissions"; import type { ActionResult } from "@/lib/safe-action-shared"; import { rcon } from "@/lib/services/rcon"; import { logStaffActivity } from "@/lib/services/staff-activity"; +/** + * Bulk actions are plain server actions whose arguments come from the client, + * so every one of them validates the payload and the target ranks first. The + * helpers below are the whole "is this allowed" contract. + */ +const MAX_BULK_USERS = 200; + +function parseUserIds(raw: unknown): number[] { + if (!Array.isArray(raw)) return []; + const ids = raw + .map((v) => (typeof v === "number" ? v : Number(v))) + .filter((v) => Number.isInteger(v) && v > 0); + return [...new Set(ids)].slice(0, MAX_BULK_USERS); +} + +function toPositiveInt(raw: unknown): number | null { + const n = typeof raw === "number" ? raw : Number(raw); + return Number.isInteger(n) && n > 0 ? n : null; +} + +function parseAmount(raw: unknown, max = 1_000_000): number | null { + const n = typeof raw === "number" ? raw : Number(raw); + return Number.isInteger(n) && n > 0 && n <= max ? n : null; +} + +function parseDuration(raw: unknown): number { + const n = typeof raw === "number" ? raw : Number(raw); + return Number.isInteger(n) && n > 0 ? Math.min(n, 60 * 60 * 24 * 365) : 0; +} + +async function guardBulkTargets( + staff: { id: number; rank: number }, + userIds: number[], +): Promise { + const highestRank = await getHighestRank(); + const superAdmin = isDynamicSuperAdmin(staff.rank, highestRank); + if (superAdmin || userIds.length === 0) return; + const rows = await db + .select({ rank: User.rank }) + .from(User) + .where(inArray(User.id, userIds)); + const blocked = rows.filter((r) => r.rank >= staff.rank); + if (blocked.length > 0) { + throw new Error( + "Cannot act on a user at or above your rank — those ids were skipped", + ); + } +} + export async function bulkUnban({ userIds, }: { userIds: number[]; }): Promise> { const staff = await requirePermission(PERMS.USERS_EDIT); - const result = await db.delete(Ban).where(inArray(Ban.userId, userIds)); + const ids = parseUserIds(userIds); + await guardBulkTargets(staff, ids); + const result = await db.delete(Ban).where(inArray(Ban.userId, ids)); const unbanned = Number(result[0]?.affectedRows ?? 0); await logStaffActivity({ staffId: staff.id, @@ -30,10 +82,7 @@ export async function bulkUnban({ description: `Unbanned ${unbanned} user(s)`, targetType: "user", }); - return { - ok: true as const, - data: { unbanned, total: userIds.length }, - }; + return { ok: true as const, data: { unbanned, total: ids.length } }; } export async function bulkBan({ @@ -46,10 +95,14 @@ export async function bulkBan({ duration: number; }): Promise> { const staff = await requirePermission(PERMS.USERS_EDIT); + const ids = parseUserIds(userIds); + const seconds = parseDuration(duration); + const reasonText = typeof reason === "string" ? reason.slice(0, 255) : ""; + await guardBulkTargets(staff, ids); const now = Math.floor(Date.now() / 1000); let banned = 0; - for (const userId of userIds) { + for (const userId of ids) { try { await db.insert(Ban).values({ userId, @@ -57,8 +110,8 @@ export async function bulkBan({ machineId: "", userStaffId: staff.id, timestamp: now, - banExpire: duration > 0 ? now + duration : 0, - banReason: reason, + banExpire: seconds > 0 ? now + seconds : 0, + banReason: reasonText, type: "account", }); banned++; @@ -92,33 +145,37 @@ export async function bulkGiveCurrency({ }> > { const staff = await requirePermission(PERMS.USERS_EDIT); + const ids = parseUserIds(userIds); + const value = parseAmount(amount); + if (!value) throw new Error("Invalid amount"); + await guardBulkTargets(staff, ids); let given = 0; const failedIds: Array<{ userId: number; reason: string }> = []; - for (const userId of userIds) { + for (const userId of ids) { try { if (type === "credits") { await db .update(User) - .set({ credits: sql`${User.credits} + ${amount}` }) + .set({ credits: sql`${User.credits} + ${value}` }) .where(eq(User.id, userId)); - await rcon.giveCredits(userId, amount); + await rcon.giveCredits(userId, value); } else if (type === "pixels") { await db .insert(UsersCurrency) - .values({ userId, type: 0, amount }) + .values({ userId, type: 0, amount: value }) .onDuplicateKeyUpdate({ - set: { amount: sql`${UsersCurrency.amount} + ${amount}` }, + set: { amount: sql`${UsersCurrency.amount} + ${value}` }, }); - await rcon.giveDuckets(userId, amount); + await rcon.giveDuckets(userId, value); } else if (type === "points") { await db .insert(UsersCurrency) - .values({ userId, type: 101, amount }) + .values({ userId, type: 101, amount: value }) .onDuplicateKeyUpdate({ - set: { amount: sql`${UsersCurrency.amount} + ${amount}` }, + set: { amount: sql`${UsersCurrency.amount} + ${value}` }, }); - await rcon.givePointsGotw(userId, amount); + await rcon.givePointsGotw(userId, value); } given++; } catch { @@ -129,7 +186,7 @@ export async function bulkGiveCurrency({ await logStaffActivity({ staffId: staff.id, action: "bulk_give_currency", - description: `Gave ${amount} ${type} to ${given} user(s)`, + description: `Gave ${value} ${type} to ${given} user(s)`, targetType: "user", }); return { @@ -152,19 +209,21 @@ export async function bulkGiveBadge({ }> > { const staff = await requirePermission(PERMS.USERS_EDIT); + const ids = parseUserIds(userIds); + const code = + typeof badgeCode === "string" ? badgeCode.trim().slice(0, 64) : ""; + if (!code) throw new Error("Invalid badge code"); + await guardBulkTargets(staff, ids); let given = 0; const failedIds: Array<{ userId: number; reason: string }> = []; - for (const userId of userIds) { + for (const userId of ids) { try { const [existing] = await db .select({ id: UsersBadges.id }) .from(UsersBadges) .where( - and( - eq(UsersBadges.userId, userId), - eq(UsersBadges.badgeCode, badgeCode), - ), + and(eq(UsersBadges.userId, userId), eq(UsersBadges.badgeCode, code)), ) .limit(1); if (!existing) { @@ -173,8 +232,10 @@ export async function bulkGiveBadge({ .from(UsersBadges) .where(eq(UsersBadges.userId, userId)); const slotId = (agg?.maxSlot ?? 0) + 1; - await db.insert(UsersBadges).values({ userId, slotId, badgeCode }); - await rcon.giveBadge(userId, badgeCode); + await db + .insert(UsersBadges) + .values({ userId, slotId, badgeCode: code }); + await rcon.giveBadge(userId, code); } given++; } catch { @@ -211,12 +272,17 @@ export async function bulkAdjustCurrency({ }> > { const staff = await requirePermission(PERMS.USERS_EDIT); + const ids = parseUserIds(userIds); if (!Number.isFinite(amount) || amount === 0) { return { ok: false as const, error: "Amount must be a non-zero number" }; } + if (Math.abs(Math.trunc(amount)) > 1_000_000) { + return { ok: false as const, error: "Amount is too large" }; + } + await guardBulkTargets(staff, ids); if (amount > 0) { - const given = await bulkGiveCurrency({ userIds, amount, type }); + const given = await bulkGiveCurrency({ userIds: ids, amount, type }); if (!given.ok) return given; if (!given.data) { return { ok: false as const, error: "Currency adjustment failed" }; @@ -235,7 +301,7 @@ export async function bulkAdjustCurrency({ let adjusted = 0; const failedIds: Array<{ userId: number; reason: string }> = []; - for (const userId of userIds) { + for (const userId of ids) { try { if (type === "credits") { const [user] = await db @@ -299,8 +365,11 @@ export async function setTradeLock({ untilUnix: number; }): Promise> { const staff = await requirePermission(PERMS.USERS_EDIT); - const until = Math.max(0, Math.trunc(untilUnix)); + const id = toPositiveInt(userId); + if (!id) return { ok: false as const, error: "Invalid user" }; + const until = Math.max(0, Math.min(Math.trunc(untilUnix), 2_000_000_000)); const locked = until > 0; + await guardBulkTargets(staff, [id]); const [user] = await db .select({ @@ -309,7 +378,7 @@ export async function setTradeLock({ online: User.online, }) .from(User) - .where(eq(User.id, userId)) + .where(eq(User.id, id)) .limit(1); if (!user) { return { ok: false as const, error: "User not found" }; @@ -331,7 +400,7 @@ export async function setTradeLock({ .where(eq(Sanctions.id, existing.id)); } else { await tx.insert(Sanctions).values({ - habboId: userId, + habboId: id, tradeLockedUntil: until, reason: locked ? "Trade lock (CMS)" : "", }); @@ -369,5 +438,5 @@ export async function setTradeLock({ targetId: userId, }); - return { ok: true as const, data: { userId, untilUnix: until } }; + return { ok: true as const, data: { userId: id, untilUnix: until } }; } diff --git a/src/actions/commandocentrum.ts b/src/actions/commandocentrum.ts index 56b9680a..92d243ab 100644 --- a/src/actions/commandocentrum.ts +++ b/src/actions/commandocentrum.ts @@ -7,12 +7,30 @@ import { db, queryRows, User } from "@/lib/db"; import { PERMS } from "@/lib/permissions"; import { adminAction } from "@/lib/safe-action"; import { ActionError, actionOk } from "@/lib/safe-action-shared"; +import { logAudit } from "@/lib/services/audit"; import { rcon } from "@/lib/services/rcon"; const PATH = "/admin/commandocentrum"; const RCON_FAIL = "RCON command failed. Is the emulator running?"; +/** Currency amounts are capped: unbounded values break the hotel economy. */ +const MAX_CURRENCY = 1_000_000; + +/** Every mutation here gets an audit entry; rank changes and RCON most of all. */ +function auditAction( + userId: number, + action: string, + targetId: number, + after: Record, +): void { + try { + logAudit({ userId, action, target: "User", targetId, after }); + } catch { + /* auditing must never fail the command it describes */ + } +} + async function requireRconOk(ok: boolean): Promise { if (!ok) throw new ActionError(RCON_FAIL); } @@ -120,9 +138,16 @@ const giveCreditsSchema = z.object({ export const giveCredits = adminAction( { permission: PERMS.RCON_EXECUTE, schema: giveCreditsSchema }, async (ctx) => { + if (ctx.data.credits > MAX_CURRENCY) { + throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`); + } await requireRconOk( await rcon.giveCredits(ctx.data.userId, ctx.data.credits), ); + auditAction(Number(ctx.session.user.id), "give_credits", ctx.data.userId, { + userId: ctx.data.userId, + amount: ctx.data.credits, + }); revalidatePath(PATH); return actionOk(); }, @@ -137,9 +162,16 @@ const giveAmountSchema = z.object({ export const giveDuckets = adminAction( { permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema }, async (ctx) => { + if (ctx.data.amount > MAX_CURRENCY) { + throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`); + } await requireRconOk( await rcon.giveDuckets(ctx.data.userId, ctx.data.amount), ); + auditAction(Number(ctx.session.user.id), "give_duckets", ctx.data.userId, { + userId: ctx.data.userId, + amount: ctx.data.amount, + }); revalidatePath(PATH); return actionOk(); }, @@ -149,9 +181,16 @@ export const giveDuckets = adminAction( export const giveDiamonds = adminAction( { permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema }, async (ctx) => { + if (ctx.data.amount > MAX_CURRENCY) { + throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`); + } await requireRconOk( await rcon.giveDiamonds(ctx.data.userId, ctx.data.amount), ); + auditAction(Number(ctx.session.user.id), "give_diamonds", ctx.data.userId, { + userId: ctx.data.userId, + amount: ctx.data.amount, + }); revalidatePath(PATH); return actionOk(); }, diff --git a/src/actions/messenger.test.ts b/src/actions/messenger.test.ts index 1864afaf..ef682f02 100644 --- a/src/actions/messenger.test.ts +++ b/src/actions/messenger.test.ts @@ -10,8 +10,13 @@ const state = vi.hoisted(() => ({ deletes: [] as unknown[], affectedDelete: 1, emptyDeleteResult: false, + isAllowed: vi.fn(async () => ({ ok: true })), })); +// The real moderation module loads the word filter through the (mocked) db, +// which would silently change the rows the offline-message assertions read. +vi.mock("@/lib/services/moderation", () => ({ isAllowed: state.isAllowed })); + vi.mock("@/lib/db", async () => { const schema = await import("@/db/schema"); const { createFakeDb } = await import("@/test/fake-db"); @@ -315,6 +320,18 @@ describe("sendOfflineMessage", () => { expect(redirected()).toBe("/messages?send_error=invalid"); }); + it("rejects content blocked by the word filter before storing it", async () => { + state.friendships = [{ id: 1 }]; + state.isAllowed.mockResolvedValue({ ok: false, reason: "bad" }); + await redirects(() => + sendOfflineMessage(fakeForm({ friendId: "2", message: "rude words" })), + ); + expect(state.isAllowed).toHaveBeenCalledWith("rude words"); + expect(state.inserts).toHaveLength(0); + expect(redirected()).toBe("/messages?send_error=invalid"); + state.isAllowed.mockResolvedValue({ ok: true }); + }); + it("stores an offline message for a friend", async () => { state.friendships = [{ id: 1 }]; await redirects(() => diff --git a/src/actions/messenger.ts b/src/actions/messenger.ts index a3c55009..9e6b4311 100644 --- a/src/actions/messenger.ts +++ b/src/actions/messenger.ts @@ -12,6 +12,7 @@ import { User, } from "@/lib/db"; import { clientIp, rateLimit } from "@/lib/rate-limit"; +import { isAllowed } from "@/lib/services/moderation"; type FriendOutcome = | "accepted" @@ -376,6 +377,8 @@ export async function sendOfflineMessage(formData: FormData): Promise { .limit(1); if (!recipient) { outcome = "invalid"; + } else if (!(await isAllowed(message)).ok) { + outcome = "invalid"; } else { await db.insert(MessengerOffline).values({ userId: friendId, diff --git a/src/actions/password-reset.test.ts b/src/actions/password-reset.test.ts index 906398cd..713e4543 100644 --- a/src/actions/password-reset.test.ts +++ b/src/actions/password-reset.test.ts @@ -1,14 +1,14 @@ // @ts-nocheck import { beforeEach, describe, expect, it, vi } from "vitest"; -const { selectLimit, insertOnDup, mockSendMail, mockRedirect } = vi.hoisted( - () => ({ +const { selectLimit, selectWhere, insertOnDup, mockSendMail, mockRedirect } = + vi.hoisted(() => ({ selectLimit: vi.fn(), insertOnDup: vi.fn().mockResolvedValue({}), + selectWhere: vi.fn(() => Promise.resolve([] as Array<{ id: number }>)), mockSendMail: vi.fn(), mockRedirect: vi.fn(), - }), -); + })); vi.mock("next/navigation", () => ({ redirect: (...args: unknown[]) => { @@ -24,6 +24,17 @@ vi.mock("@/lib/db", () => { from: vi.fn(() => ({ where: vi.fn(() => ({ limit: selectLimit, + // Matches the deterministic `.orderBy(asc(User.id))` list + // reads used to resolve duplicate addresses. + orderBy: vi.fn(() => ({ + // biome-ignore lint/suspicious/noThenProperty: Drizzle query thenable mock + then( + resolve: (v: unknown) => void, + reject: (e: unknown) => void, + ) { + return Promise.resolve(selectWhere()).then(resolve, reject); + }, + })), })), })), })), @@ -70,13 +81,14 @@ beforeEach(() => { describe("requestReset", () => { it("sends a reset email when the user exists", async () => { selectLimit.mockResolvedValue([{ id: 1 }]); + selectWhere.mockResolvedValue([{ id: 1 }]); const fd = new FormData(); fd.set("email", "user@example.com"); await expect(requestReset(fd)).rejects.toThrow("redirect"); - expect(selectLimit).toHaveBeenCalled(); + expect(selectWhere).toHaveBeenCalled(); expect(insertOnDup).toHaveBeenCalled(); expect(mockSendMail).toHaveBeenCalledWith( "user@example.com", @@ -87,6 +99,7 @@ describe("requestReset", () => { it("does not send email when user is not found", async () => { selectLimit.mockResolvedValue([]); + selectWhere.mockResolvedValue([]); const fd = new FormData(); fd.set("email", "unknown@example.com"); diff --git a/src/actions/password-reset.ts b/src/actions/password-reset.ts index 3e760333..93794de5 100644 --- a/src/actions/password-reset.ts +++ b/src/actions/password-reset.ts @@ -1,11 +1,14 @@ "use server"; import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { asc, eq } from "drizzle-orm"; import { redirect } from "next/navigation"; import { env } from "@/env"; +import { invalidateLoginCache } from "@/lib/auth/login-core"; import { hashPassword } from "@/lib/auth/password"; +import { revokeUserCredentials } from "@/lib/auth/session-revocation"; import { db, PasswordReset, User } from "@/lib/db"; +import { logger } from "@/lib/logger"; import { clientIp, rateLimit } from "@/lib/rate-limit"; import { logServerError } from "@/lib/server-log"; import { captchaConfig, verifyCaptcha } from "@/lib/services/captcha"; @@ -17,6 +20,17 @@ function sha256(s: string): string { return createHash("sha256").update(s).digest("hex"); } +/** + * Back to the reset form with a *code*, never with the human-readable message: + * a raw `?error=` value would be rendered on our own domain, which is a + * perfect phishing skeleton. The page maps each code to a translation. + */ +function errorRedirect(email: string, token: string, code: string): never { + return redirect( + `/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${code}`, + ); +} + export async function requestReset(formData: FormData): Promise { const email = String(formData.get("email") ?? "") .normalize("NFC") @@ -40,12 +54,23 @@ export async function requestReset(formData: FormData): Promise { // Always respond the same way so we don't reveal which emails exist. if (allowed && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { try { - const [user] = await db + const matches = await db .select({ id: User.id }) .from(User) .where(eq(User.mail, email)) - .limit(1); + .orderBy(asc(User.id)); + if (matches.length > 1) { + logger.warn("Password reset address is not unique", { + email, + accountCount: matches.length, + using: matches[0]?.id, + }); + } + const user = matches[0]; if (user) { + // Duplicate addresses exist on legacy databases; resetting the + // *oldest* account keeps the choice deterministic instead of + // "whatever row the engine returns first". const token = randomBytes(32).toString("hex"); const hashed = sha256(token); const createdAt = new Date(); @@ -80,13 +105,11 @@ export async function resetPassword(formData: FormData): Promise { // 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")}`, - ); + redirect(errorRedirect(email, token, "ratelimit")); } - let error: string | null = null; - if (password.length < 12) error = "Password must be at least 12 characters"; + let error: "password" | "invalid" | "failed" | null = null; + if (password.length < 12) error = "password"; if (!error) { try { @@ -107,20 +130,29 @@ export async function resetPassword(formData: FormData): Promise { row != null && a.length === b.length && timingSafeEqual(a, b); if (!row || !fresh || !match) { - error = "This reset link is invalid or has expired"; + error = "invalid"; } else { - const [user] = await db + const matches = await db .select({ id: User.id }) .from(User) .where(eq(User.mail, email)) - .limit(1); + .orderBy(asc(User.id)); + const user = matches[0]; if (!user) { - error = "Account not found"; + error = "invalid"; } else { - await db - .update(User) - .set({ password: await hashPassword(password) }) - .where(eq(User.id, user.id)); + const newHash = await hashPassword(password); + // A password change has to end every existing session: the + // popular reason for resetting is a compromised account, and a + // stolen cookie/API token must not outlive the reset. + await Promise.all([ + db + .update(User) + .set({ password: newHash }) + .where(eq(User.id, user.id)), + revokeUserCredentials(user.id), + ]); + await invalidateLoginCache(email); await db .delete(PasswordReset) .where(eq(PasswordReset.email, email)) @@ -132,14 +164,12 @@ export async function resetPassword(formData: FormData): Promise { } } } catch { - error = "Could not reset the password — try again"; + error = "failed"; } } if (error) { - redirect( - `/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent(error)}`, - ); + redirect(errorRedirect(email, token, error)); } redirect("/login?reset=1"); } diff --git a/src/actions/permissions.ts b/src/actions/permissions.ts index d75fe7e4..b9e996d1 100644 --- a/src/actions/permissions.ts +++ b/src/actions/permissions.ts @@ -175,8 +175,10 @@ export const setCmsPermissions = adminAction( ); /** - * Re-apply the same grant repair as migration 0018: - * - ranks with admin.dashboard get all admin.* + * Re-apply the grant repair from migration 0018/0034: + * - ranks with admin.dashboard get all admin.*.view (read-only: the sidebar + * needs to open, nothing more — a blanket `admin.%` grant here is what + * promoted rank 6 to full admin) * - ranks >= 6 get admin.*.view + dashboard * - ranks >= 7 get edit/manage/execute tools used by the sidebar */ @@ -187,7 +189,9 @@ export const repairAdminNavAclGrants = adminAction( INSERT INTO \`acl_model_permissions\` (\`model_type\`, \`model_id\`, \`permission_id\`) SELECT 'Role', ar.id, ap.id FROM \`acl_roles\` ar - JOIN \`acl_permissions\` ap ON ap.slug LIKE 'admin.%' + -- View slugs only: widening this to all admin.* turned "can open the + -- panel" into "is a full admin" for every mid rank (see 0034). + JOIN \`acl_permissions\` ap ON ap.slug LIKE 'admin.%' AND ap.slug LIKE '%.view' WHERE EXISTS ( SELECT 1 FROM \`acl_model_permissions\` amp diff --git a/src/actions/rooms.test.ts b/src/actions/rooms.test.ts index a10ce18a..8aa38669 100644 --- a/src/actions/rooms.test.ts +++ b/src/actions/rooms.test.ts @@ -76,14 +76,17 @@ describe("rooms actions", () => { }); state.del.mockResolvedValue([{ affectedRows: 1 }]); state.update.mockResolvedValue([{ affectedRows: 1 }]); + // The item/room ownership lookups must find their row. + state.roomRows = [{ name: "Lobby" }, { id: 4 }]; }); it("requires the ROOMS_EDIT permission for updateRoomItem", async () => { - await updateRoomItem({ roomId: 9, itemId: 4, custom: "x" }); + // `custom` is not an allow-listed column, so it must never reach `.set()`. + await updateRoomItem({ roomId: 9, itemId: 4, rot: 4, custom: "x" }); expect(state.requirePermission).toHaveBeenCalledWith("admin.room.edit"); expect(state.update).toHaveBeenCalledWith( Items, - { custom: "x" }, + { rot: 4 }, expect.anything(), ); expect(state.logStaffActivity).toHaveBeenCalledWith( diff --git a/src/actions/rooms.ts b/src/actions/rooms.ts index 6b14181b..51513834 100644 --- a/src/actions/rooms.ts +++ b/src/actions/rooms.ts @@ -9,16 +9,63 @@ import { rcon } from "@/lib/services/rcon"; import { logStaffActivity } from "@/lib/services/staff-activity"; import { notify } from "@/lib/services/webhook"; +// Only these columns may be patched from the client. Spreading the whole payload +// into `.set()` let a caller rewrite roomId/userId/extraData of any row, which +// is mass assignment and IDOR in one. +const ROOM_ITEM_FIELDS = [ + "wallPos", + "x", + "y", + "z", + "rot", + "extraData", + "wiredData", + "limitedData", + "guildId", +] as const; + +const ROOM_FIELDS = ["name", "description", "state", "usersMax"] as const; + +function pickAllowed( + fields: Record, + allowed: readonly string[], +): Record { + const out: Record = {}; + for (const key of allowed) { + if (Object.hasOwn(fields, key) && fields[key] !== undefined) { + out[key] = fields[key]; + } + } + return out; +} + +function toPositiveInt(value: unknown): number | null { + const n = typeof value === "number" ? value : Number(value); + return Number.isInteger(n) && n > 0 ? n : null; +} + export async function updateRoomItem(payload: Record) { const staff = await requirePermission(PERMS.ROOMS_EDIT); - const { roomId, itemId, ...data } = payload as { - roomId: number; - itemId: number; - [key: string]: unknown; - }; + const roomId = toPositiveInt(payload.roomId); + const itemId = toPositiveInt(payload.itemId); + if (!roomId || !itemId) { + throw new Error("Invalid room or item id"); + } + // The item must belong to the room the staff member is editing. + const [item] = await db + .select({ id: Items.id }) + .from(Items) + .where(and(eq(Items.id, itemId), eq(Items.roomId, roomId))) + .limit(1); + if (!item) throw new Error("Item not found in this room"); + await db .update(Items) - .set(data as Partial) + .set( + pickAllowed(payload, ROOM_ITEM_FIELDS) as Partial< + typeof Items.$inferInsert + >, + ) .where(eq(Items.id, itemId)); await logStaffActivity({ staffId: staff.id, @@ -117,24 +164,20 @@ export async function deleteRoom({ id }: { id: number }) { revalidatePath("/admin/rooms"); } -export async function updateRoom({ - id, - ...data -}: { - id: number; - name?: string; - description?: string; - state?: string; - usersMax?: number; -}) { +export async function updateRoom({ id, ...data }: Record) { const staff = await requirePermission(PERMS.ROOMS_EDIT); - await db.update(Rooms).set(data).where(eq(Rooms.id, id)); + const roomId = toPositiveInt(id); + if (!roomId) throw new Error("Invalid room id"); + await db + .update(Rooms) + .set(pickAllowed(data, ROOM_FIELDS) as Partial) + .where(eq(Rooms.id, roomId)); await logStaffActivity({ staffId: staff.id, action: "room_update", - description: `Updated room #${id}`, + description: `Updated room #${roomId}`, targetType: "room", - targetId: id, + targetId: roomId, }); - revalidatePath(`/admin/rooms/${id}`); + revalidatePath(`/admin/rooms/${roomId}`); } diff --git a/src/actions/social.test.ts b/src/actions/social.test.ts index 44e97de4..6d10a23b 100644 --- a/src/actions/social.test.ts +++ b/src/actions/social.test.ts @@ -14,8 +14,13 @@ const state = vi.hoisted(() => ({ selectQueue: [] as Queue, rows: [] as Array>, failInsert: false, + isAllowed: vi.fn(async () => ({ ok: true })), })); +// The real moderation module loads the word filter through the (mocked) db +// select queue, which would shift the rows the forum assertions rely on. +vi.mock("@/lib/services/moderation", () => ({ isAllowed: state.isAllowed })); + vi.mock("next/cache", () => ({ revalidatePath: state.revalidatePath })); vi.mock("next/navigation", () => ({ redirect: (path: string) => { @@ -210,6 +215,7 @@ describe("postThread", () => { state.failInsert = false; state.selectQueue = []; state.rows = []; + state.isAllowed.mockResolvedValue({ ok: true }); state.transaction.mockImplementation( async (fn: (tx: unknown) => Promise, txDb: unknown) => fn(txDb), ); @@ -283,6 +289,18 @@ describe("postThread", () => { expect(state.insert).not.toHaveBeenCalled(); }); + it("rejects content blocked by the word filter before hitting the db", async () => { + state.isAllowed.mockResolvedValue({ ok: false, reason: "bad" }); + state.selectQueue = [[{ id: 10 }]]; + await expect(postThread(threadForm())).rejects.toThrow( + "/guilds/10/forum/new?error=invalid", + ); + expect(state.isAllowed).toHaveBeenCalledWith( + "Welcome thread Hello from the community", + ); + expect(state.insert).not.toHaveBeenCalled(); + }); + it("reports not_found when the guild does not exist", async () => { state.selectQueue = [[]]; await expect(postThread(threadForm())).rejects.toThrow( @@ -324,6 +342,7 @@ describe("replyToThread", () => { state.failInsert = false; state.selectQueue = []; state.rows = []; + state.isAllowed.mockResolvedValue({ ok: true }); state.transaction.mockImplementation( async (fn: (tx: unknown) => Promise, txDb: unknown) => fn(txDb), ); @@ -361,6 +380,16 @@ describe("replyToThread", () => { expect(state.update.mock.calls[0][1]).toMatchObject({ postsCount: 1 }); }); + it("rejects a reply blocked by the word filter before hitting the db", async () => { + state.isAllowed.mockResolvedValue({ ok: false, reason: "bad" }); + state.selectQueue = [[{ id: 20, locked: 0, postsCount: 3 }]]; + await expect(replyToThread(replyForm())).rejects.toThrow( + "/guilds/10/forum/20?error=invalid", + ); + expect(state.isAllowed).toHaveBeenCalledWith("A thoughtful reply"); + expect(state.insert).not.toHaveBeenCalled(); + }); + it("rejects missing or non-positive ids by redirecting to /guilds", async () => { await expect(replyToThread(replyForm({ guildId: "abc" }))).rejects.toThrow( "/guilds", diff --git a/src/actions/social.ts b/src/actions/social.ts index 9dde1c08..98357a72 100644 --- a/src/actions/social.ts +++ b/src/actions/social.ts @@ -13,6 +13,7 @@ import { MessengerFriendships, } from "@/lib/db"; import { clientIp, rateLimit } from "@/lib/rate-limit"; +import { isAllowed } from "@/lib/services/moderation"; // Guild forum subjects are VARCHAR(255); the comment/message body lives in // guilds_forums_comments.message which is TEXT. Keep the first post's message @@ -235,6 +236,8 @@ export async function postThread(formData: FormData): Promise { .slice(0, MESSAGE_MAX); if (!subject || !message) { outcome = "invalid"; + } else if (!(await isAllowed(`${subject} ${message}`)).ok) { + outcome = "invalid"; } else { const now = Math.floor(Date.now() / 1000); @@ -326,6 +329,8 @@ export async function replyToThread(formData: FormData): Promise { .slice(0, MESSAGE_MAX); if (!message) { outcome = "invalid"; + } else if (!(await isAllowed(message)).ok) { + outcome = "invalid"; } else { const now = Math.floor(Date.now() / 1000); diff --git a/src/actions/twofactor.ts b/src/actions/twofactor.ts index ab96bb36..40b1e1fb 100644 --- a/src/actions/twofactor.ts +++ b/src/actions/twofactor.ts @@ -78,6 +78,22 @@ async function verifyTwoFactorCode( export async function beginTwoFactor(): Promise { const id = await sessionUserId(); if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey"); + + if (!(await rateLimit(`2fa-begin:${id}`, 5, 30_000)).ok) + redirect("/settings/2fa?error=ratelimit"); + + // Re-running this action while 2FA is confirmed would be a silent *downgrade* + // (the new secret is stored unconfirmed, and unconfirmed means "login gate + // off"), so the existing setup has to be disabled through the proper flow + // first: a valid code, not just an authenticated session. + const [current] = await db + .select({ twoFactorConfirmedAt: User.twoFactorConfirmedAt }) + .from(User) + .where(eq(User.id, id)) + .limit(1); + if (current?.twoFactorConfirmedAt) + redirect("/settings/2fa?error=alreadyenabled"); + const secret = generateTotpSecret(); const encrypted = new LaravelEncrypter(env.APP_KEY).encrypt(secret); const codes = generateRecoveryCodes(); @@ -104,12 +120,19 @@ export async function confirmTwoFactor(formData: FormData): Promise { .normalize("NFC") .trim(); - const { ok } = await verifyTwoFactorCode(id, code); + const { ok, updatedRecoveryCodes } = await verifyTwoFactorCode(id, code); if (!ok) redirect("/settings/2fa?error=badcode"); + // A recovery code spends itself on use, so persist the remainder together + // with the confirmation instead of dropping the caller's own update. await db .update(User) - .set({ twoFactorConfirmedAt: new Date() }) + .set({ + twoFactorConfirmedAt: new Date(), + ...(updatedRecoveryCodes !== undefined + ? { twoFactorRecoveryCodes: updatedRecoveryCodes } + : {}), + }) .where(eq(User.id, id)); redirect("/settings/2fa?enabled=1"); } diff --git a/src/actions/user-settings.test.ts b/src/actions/user-settings.test.ts index 267f9572..a84cccc4 100644 --- a/src/actions/user-settings.test.ts +++ b/src/actions/user-settings.test.ts @@ -8,6 +8,7 @@ const state = vi.hoisted(() => ({ updateCall: undefined as unknown, rconSetMotto: vi.fn(), failDbUpdate: false, + isAllowed: vi.fn(async () => ({ ok: true })), })); const databaseErrorClass = vi.hoisted( @@ -63,6 +64,10 @@ vi.mock("@/lib/services/rcon", () => ({ rcon: { setMotto: state.rconSetMotto }, })); +vi.mock("@/lib/services/moderation", () => ({ + isAllowed: state.isAllowed, +})); + const mockRevalidatePath = vi.hoisted(() => vi.fn()); vi.mock("next/cache", () => ({ revalidatePath: mockRevalidatePath })); @@ -98,6 +103,7 @@ beforeEach(() => { state.updateCall = undefined; state.rconSetMotto.mockResolvedValue(true); state.failDbUpdate = false; + state.isAllowed.mockResolvedValue({ ok: true }); }); describe("updateMotto", () => { @@ -141,6 +147,18 @@ describe("updateMotto", () => { }); }); +describe("updateMotto word filter", () => { + it("rejects a motto blocked by the word filter before persisting", async () => { + state.isAllowed.mockResolvedValue({ ok: false, reason: "bad" }); + await expect(updateMotto(mockingForm("bad motto"))).rejects.toThrow( + databaseErrorClass, + ); + expect(state.isAllowed).toHaveBeenCalledWith("bad motto"); + expect(state.updateCall).toBeUndefined(); + expect(state.rconSetMotto).not.toHaveBeenCalled(); + }); +}); + describe("updateMottoAction", () => { it("denies unauthenticated callers", async () => { state.auth.mockResolvedValue(null); diff --git a/src/actions/user-settings.ts b/src/actions/user-settings.ts index 6174e95f..3d666ee4 100644 --- a/src/actions/user-settings.ts +++ b/src/actions/user-settings.ts @@ -6,6 +6,7 @@ import { z } from "zod"; import { db, User } from "@/lib/db"; import { actionOk, authAction } from "@/lib/foundation/action"; import { DatabaseError } from "@/lib/foundation/errors"; +import { isAllowed } from "@/lib/services/moderation"; import { rcon } from "@/lib/services/rcon"; const MOTTO_MAX = 127; @@ -16,7 +17,14 @@ const mottoSchema = z.object({ .max(MOTTO_MAX, `Motto must be at most ${MOTTO_MAX} characters`), }); +async function assertMottoAllowed(motto: string): Promise { + if (!(await isAllowed(motto)).ok) { + throw new DatabaseError("Motto not allowed"); + } +} + const updateMottoAction = authAction({ schema: mottoSchema }, async (ctx) => { + await assertMottoAllowed(ctx.data.motto); try { await db .update(User) diff --git a/src/actions/users.test.ts b/src/actions/users.test.ts index 81047451..e53d5dbd 100644 --- a/src/actions/users.test.ts +++ b/src/actions/users.test.ts @@ -62,6 +62,9 @@ vi.mock("@/lib/permissions", () => ({ USERS_BAN: "users.ban", USERS_RESET_PASSWORD: "users.reset_password", }, + // Staff in the fixtures is rank 7 and the hotel's top rank is 10, so rank + // guards act as "below-your-own-rank only". + getHighestRank: vi.fn(() => Promise.resolve(10)), })); vi.mock("@/lib/safe-action", () => ({ @@ -77,6 +80,10 @@ vi.mock("@/lib/services/audit", () => ({ logAudit: vi.fn(), })); +vi.mock("@/lib/auth/session-revocation", () => ({ + revokeUserCredentials: vi.fn(() => Promise.resolve()), +})); + vi.mock("@/lib/services/webhook", () => ({ notify: vi.fn(), })); diff --git a/src/actions/users.ts b/src/actions/users.ts index d4526acc..c3b76875 100644 --- a/src/actions/users.ts +++ b/src/actions/users.ts @@ -3,8 +3,10 @@ import crypto from "node:crypto"; import { and, eq } from "drizzle-orm"; import { z } from "zod"; +import { isDynamicSuperAdmin } from "@/lib/admin/authorization-policy"; import { invalidateLoginCache } from "@/lib/auth"; import { hashPassword } from "@/lib/auth/password"; +import { revokeUserCredentials } from "@/lib/auth/session-revocation"; import { Ban, db, @@ -13,7 +15,7 @@ import { UsersCurrency, UsersSettings, } from "@/lib/db"; -import { PERMS } from "@/lib/permissions"; +import { getHighestRank, PERMS } from "@/lib/permissions"; import { adminAction } from "@/lib/safe-action"; import { ActionError, actionOk } from "@/lib/safe-action-shared"; import { logAudit } from "@/lib/services/audit"; @@ -54,8 +56,9 @@ export const createUser = adminAction( { permission: PERMS.USERS_EDIT, schema: createUserSchema }, async (ctx) => { const { username, mail, password, rank, motto } = ctx.data; - - if (rank >= ctx.session.user.rank && ctx.session.user.rank < 7) { + const actorRank = ctx.session.user.rank; + const highestRank = await getHighestRank(); + if (rank >= actorRank && !isDynamicSuperAdmin(actorRank, highestRank)) { throw new ActionError("Cannot assign rank equal or higher than your own"); } @@ -130,7 +133,7 @@ export const updateUser = adminAction( if ( userData.rank !== undefined && userData.rank >= ctx.session.user.rank && - ctx.session.user.rank < 7 + !isDynamicSuperAdmin(ctx.session.user.rank, await getHighestRank()) ) { throw new ActionError("Cannot assign rank equal or higher than your own"); } @@ -144,7 +147,15 @@ export const updateUser = adminAction( motto: string; credits: number; pixels: number; + mailVerified?: string; }>; + // A changed address has to prove itself again: leaving mail_verified + // set would keep every mail send (resets, notifications) pointed at an + // inbox nobody confirmed, and would silently bypass the "verified + // accounts only" gate. + if (patch.mail !== undefined && patch.mail !== targetUser.mail) { + patch.mailVerified = "0"; + } if (Object.keys(patch).length > 0) { await db.update(User).set(patch).where(eq(User.id, id)); } @@ -331,7 +342,14 @@ async function guardRank(targetUserId: number, sessionRank: number) { .where(eq(User.id, targetUserId)) .limit(1); if (!target) throw new ActionError("User not found"); - if (target.rank >= sessionRank && sessionRank < 7) { + // The owner is whoever holds the hotel's highest rank *today*. The old + // `sessionRank < 7` shortcut handed every rank-7 account owner powers on + // any hotel whose top rank is 8+, which makes it a plain escalation. + const highestRank = await getHighestRank(); + if ( + target.rank >= sessionRank && + !isDynamicSuperAdmin(sessionRank, highestRank) + ) { throw new ActionError("Cannot modify user with equal or higher rank"); } return target; @@ -358,6 +376,9 @@ export const resetPassword = adminAction( .update(User) .set({ password: hashed }) .where(eq(User.id, ctx.data.userId)); + // A staff-issued password must also end the user's live sessions: this + // action exists precisely for "account compromised" situations. + await revokeUserCredentials(ctx.data.userId); invalidateLoginCache(target.username); logAudit({ @@ -419,9 +440,19 @@ const alertUserSchema = z.object({ export const alertUser = adminAction( { permission: PERMS.USERS_EDIT, schema: alertUserSchema }, async (ctx) => { + const target = await guardRank(ctx.data.userId, ctx.session.user.rank); const success = await rcon.alertUser(ctx.data.userId, ctx.data.message); if (!success) throw new ActionError("Failed to send alert. Is the emulator running?"); + + logAudit({ + userId: ctx.session.user.id, + action: "user_alert", + target: "User", + targetId: ctx.data.userId, + after: { message: ctx.data.message, username: target.username }, + }); + return actionOk(); }, ); diff --git a/src/actions/verify.ts b/src/actions/verify.ts index a950034e..7737f20a 100644 --- a/src/actions/verify.ts +++ b/src/actions/verify.ts @@ -36,6 +36,11 @@ export async function resendVerification( if (!(await rateLimit(`verify:resend:${ip}`, 3, 10 * 60_000)).ok) { return { ok: false, error: "rateLimited" }; } + // Same cooldown keyed on the address, so rotating IPs cannot be used to + // mail-bomb an arbitrary inbox with "verify your email". + if (!(await rateLimit(`verify:resend:email:${email}`, 3, 10 * 60_000)).ok) { + return { ok: false, error: "rateLimited" }; + } try { const [user] = await db diff --git a/src/app/(site)/apply/staff/page.tsx b/src/app/(site)/apply/staff/page.tsx index cebae932..7aa7df45 100644 --- a/src/app/(site)/apply/staff/page.tsx +++ b/src/app/(site)/apply/staff/page.tsx @@ -110,7 +110,7 @@ export default async function ApplyStaffPage({ const appliedRankIds = new Set(myApps.map((a) => a.rankId)); return ( -
+
{submitted === "1" ? (
{t("success.submitted")} @@ -233,6 +233,6 @@ export default async function ApplyStaffPage({ })}
)} -
+ ); } diff --git a/src/app/(site)/apply/team/page.tsx b/src/app/(site)/apply/team/page.tsx index fad2aa3f..64d33ca2 100644 --- a/src/app/(site)/apply/team/page.tsx +++ b/src/app/(site)/apply/team/page.tsx @@ -89,7 +89,7 @@ export default async function ApplyTeamPage({ const appliedTeamIds = new Set(myApps.map((a) => a.rankId)); return ( -
+
{submitted === "1" ? (
{t("success.submitted")} @@ -199,6 +199,6 @@ export default async function ApplyTeamPage({ })}
)} -
+ ); } diff --git a/src/app/(site)/badges/page.tsx b/src/app/(site)/badges/page.tsx index 7c05d3b5..378014c4 100644 --- a/src/app/(site)/badges/page.tsx +++ b/src/app/(site)/badges/page.tsx @@ -30,7 +30,7 @@ export default async function BadgesPage() { .catch(() => []); return ( -
+
@@ -76,6 +76,6 @@ export default async function BadgesPage() { )} -
+ ); } diff --git a/src/app/(site)/banned/page.tsx b/src/app/(site)/banned/page.tsx index 4df2bfa3..defad995 100644 --- a/src/app/(site)/banned/page.tsx +++ b/src/app/(site)/banned/page.tsx @@ -52,7 +52,7 @@ export default async function BannedPage() { }); return ( -
+

{t("body")}

{reason ? ( @@ -65,6 +65,6 @@ export default async function BannedPage() { {t("contactStaff")}

-
+ ); } diff --git a/src/app/(site)/community/page.tsx b/src/app/(site)/community/page.tsx index 63576e72..5c34743f 100644 --- a/src/app/(site)/community/page.tsx +++ b/src/app/(site)/community/page.tsx @@ -54,7 +54,7 @@ export default function CommunityPage() { const t = useTranslations("pages.community"); return ( -
+
@@ -84,6 +84,6 @@ export default function CommunityPage() { ))}
-
+ ); } diff --git a/src/app/(site)/developers/page.tsx b/src/app/(site)/developers/page.tsx index b07f7565..29860ae6 100644 --- a/src/app/(site)/developers/page.tsx +++ b/src/app/(site)/developers/page.tsx @@ -398,7 +398,7 @@ export default function DevelopersPage() { const totalEndpoints = GROUPS.reduce((n, g) => n + g.endpoints.length, 0); return ( -
+
))} -
+ ); } diff --git a/src/app/(site)/draw-badge/page.tsx b/src/app/(site)/draw-badge/page.tsx index e1588657..798b7736 100644 --- a/src/app/(site)/draw-badge/page.tsx +++ b/src/app/(site)/draw-badge/page.tsx @@ -102,7 +102,7 @@ export default async function DrawBadgePage({ } return ( -
+
)} -
+ ); } diff --git a/src/app/(site)/events/[slugOrId]/page.tsx b/src/app/(site)/events/[slugOrId]/page.tsx index 742942c8..74ca78dc 100644 --- a/src/app/(site)/events/[slugOrId]/page.tsx +++ b/src/app/(site)/events/[slugOrId]/page.tsx @@ -142,7 +142,7 @@ export default async function EventDetailPage({ else if (isFull) disabledReason = t("eventFull"); return ( -
+

{t("back")}

@@ -259,6 +259,6 @@ export default async function EventDetailPage({ ) : null} -
+ ); } diff --git a/src/app/(site)/events/page.tsx b/src/app/(site)/events/page.tsx index 42775135..f9ca1cb3 100644 --- a/src/app/(site)/events/page.tsx +++ b/src/app/(site)/events/page.tsx @@ -69,7 +69,7 @@ async function EventsPage({ const href = (page: number) => `/events?${new URLSearchParams({ status: result?.status ?? "all", week: result?.week ?? "", mine: params.mine ?? "", page: String(page) })}`; return ( -
+
@@ -272,7 +272,7 @@ async function EventsPage({ )} -
+ ); } diff --git a/src/app/(site)/forgot/page.tsx b/src/app/(site)/forgot/page.tsx index c32dfe64..a5f49250 100644 --- a/src/app/(site)/forgot/page.tsx +++ b/src/app/(site)/forgot/page.tsx @@ -1,3 +1,4 @@ +import type { Metadata } from "next"; import { headers } from "next/headers"; import { getTranslations } from "next-intl/server"; import { requestReset } from "@/actions/password-reset"; @@ -6,6 +7,15 @@ import Link from "@/components/link"; import { ContentCard } from "@/components/public/ui"; import { captchaConfig } from "@/lib/services/captcha"; +export async function generateMetadata(): Promise { + const t = await getTranslations("pages.forgot"); + return { + title: t("title"), + description: t("subtitle"), + robots: { index: false, follow: false }, + }; +} + export default async function ForgotPage({ searchParams, }: { @@ -17,12 +27,39 @@ export default async function ForgotPage({ const nonce = (await headers()).get("x-nonce") ?? undefined; return ( -
+
{sent ? ( -

- {t("sentNotice")} -

+ <> +

+ {t("sentNotice")} +

+ {/* A mail that never arrived must be retryable from here, + otherwise the visitor is stuck on a dead end. */} +
+ + + + + ) : (
{t("backToLogin")}

-
+ ); } diff --git a/src/app/(site)/friends/page.tsx b/src/app/(site)/friends/page.tsx index 946b7241..fe686c53 100644 --- a/src/app/(site)/friends/page.tsx +++ b/src/app/(site)/friends/page.tsx @@ -102,7 +102,7 @@ export default async function FriendsPage({ : null; return ( -
+
{removed === "1" ? (
{t("success.removed")} @@ -180,6 +180,6 @@ export default async function FriendsPage({
)} -
+ ); } diff --git a/src/app/(site)/guilds/[id]/forum/[threadId]/page.tsx b/src/app/(site)/guilds/[id]/forum/[threadId]/page.tsx index f5dc495a..ec41537b 100644 --- a/src/app/(site)/guilds/[id]/forum/[threadId]/page.tsx +++ b/src/app/(site)/guilds/[id]/forum/[threadId]/page.tsx @@ -103,11 +103,11 @@ export default async function GuildForumThreadPage({ } catch (error) { publicReadFailure("guild.thread")(error); return ( -
+
-
+ ); } @@ -173,7 +173,7 @@ export default async function GuildForumThreadPage({ : null; return ( -
+
{replied === "1" ? (
{t("success.replied")} @@ -317,6 +317,6 @@ export default async function GuildForumThreadPage({ {t("loginToReply")} {t("loginLink")}

)} -
+ ); } diff --git a/src/app/(site)/guilds/[id]/forum/new/page.tsx b/src/app/(site)/guilds/[id]/forum/new/page.tsx index 452d4bba..1fae630a 100644 --- a/src/app/(site)/guilds/[id]/forum/new/page.tsx +++ b/src/app/(site)/guilds/[id]/forum/new/page.tsx @@ -70,7 +70,7 @@ export default async function NewThreadPage({ : null; return ( -
+
{errorMessage ? (
{errorMessage} @@ -132,6 +132,6 @@ export default async function NewThreadPage({
-
+ ); } diff --git a/src/app/(site)/guilds/[id]/forum/page.tsx b/src/app/(site)/guilds/[id]/forum/page.tsx index 106bf6d5..672824da 100644 --- a/src/app/(site)/guilds/[id]/forum/page.tsx +++ b/src/app/(site)/guilds/[id]/forum/page.tsx @@ -67,11 +67,11 @@ export default async function GuildForumPage({ } catch (error) { publicReadFailure("guild.forum")(error); return ( -
+
-
+ ); } @@ -135,7 +135,7 @@ export default async function GuildForumPage({ const usernameById = new Map(users.map((u) => [u.id, u.username])); return ( -
+
{posted === "1" ? (
{t("success.posted")} @@ -240,6 +240,6 @@ export default async function GuildForumPage({ )} -
+ ); } diff --git a/src/app/(site)/guilds/[id]/page.tsx b/src/app/(site)/guilds/[id]/page.tsx index 281b3f8c..bd15eba7 100644 --- a/src/app/(site)/guilds/[id]/page.tsx +++ b/src/app/(site)/guilds/[id]/page.tsx @@ -55,11 +55,11 @@ export default async function GuildPage({ } catch (error) { publicReadFailure("guild.detail")(error); return ( -
+
-
+ ); } @@ -139,7 +139,7 @@ export default async function GuildPage({ const created = formatDate(new Date(guild.dateCreated * 1000), "date"); return ( -
+

{t("allGuilds")}

@@ -251,6 +251,6 @@ export default async function GuildPage({ )} -
+ ); } diff --git a/src/app/(site)/guilds/page.tsx b/src/app/(site)/guilds/page.tsx index f700f58a..67330571 100644 --- a/src/app/(site)/guilds/page.tsx +++ b/src/app/(site)/guilds/page.tsx @@ -50,7 +50,7 @@ export default async function GuildsPage() { const guilds = await getGuilds(); return ( -
+
@@ -98,6 +98,6 @@ export default async function GuildsPage() { )} -
+ ); } diff --git a/src/app/(site)/help/[category]/page.tsx b/src/app/(site)/help/[category]/page.tsx index 0114203c..5ef771f5 100644 --- a/src/app/(site)/help/[category]/page.tsx +++ b/src/app/(site)/help/[category]/page.tsx @@ -103,7 +103,7 @@ export default async function HelpCategoryPage({ const hasButton = Boolean(cat.buttonText && cat.buttonText.trim() !== ""); return ( -
+

{t("back")}

@@ -162,6 +162,6 @@ export default async function HelpCategoryPage({ ) : null} -
+ ); } diff --git a/src/app/(site)/help/page.tsx b/src/app/(site)/help/page.tsx index 077b8bd3..06f4d42e 100644 --- a/src/app/(site)/help/page.tsx +++ b/src/app/(site)/help/page.tsx @@ -127,7 +127,7 @@ export default async function HelpCenterPage() { } return ( -
+
)} -
+ ); } diff --git a/src/app/(site)/help/tickets/[id]/page.tsx b/src/app/(site)/help/tickets/[id]/page.tsx index fe95b7db..59c2a1e3 100644 --- a/src/app/(site)/help/tickets/[id]/page.tsx +++ b/src/app/(site)/help/tickets/[id]/page.tsx @@ -157,7 +157,7 @@ export default async function HelpTicketDetailPage({ ]; return ( -
+
{replied === "1" ? (
{t("success.replied")} @@ -302,6 +302,6 @@ export default async function HelpTicketDetailPage({ {t("closedHint")}

)} -
+ ); } diff --git a/src/app/(site)/help/tickets/page.tsx b/src/app/(site)/help/tickets/page.tsx index 17f0667a..44307317 100644 --- a/src/app/(site)/help/tickets/page.tsx +++ b/src/app/(site)/help/tickets/page.tsx @@ -67,7 +67,7 @@ export default async function HelpTicketsPage({ : null; return ( -
+
{created === "1" ? (
{t("success.created")} @@ -167,6 +167,6 @@ export default async function HelpTicketsPage({ )} -
+ ); } diff --git a/src/app/(site)/layout.tsx b/src/app/(site)/layout.tsx index 4aa4b4ae..ab8bbfa9 100644 --- a/src/app/(site)/layout.tsx +++ b/src/app/(site)/layout.tsx @@ -31,19 +31,18 @@ export default async function SiteLayout({ return ( <> - {session?.user?.id ? ( - <> -
- -
-
- -
-
- -
- - ) : null} + {/* Site chrome is public: hiding it all for anonymous visitors used to + strand them — from /news, /leaderboard or /shop there was no way to + reach any other page at all. */} +
+ +
+
+ +
+
+ +
{ const t = await getTranslations("pages.leaderboard"); @@ -52,7 +53,17 @@ function formatValue(key: TabKey, value: number): string { return value.toLocaleString(); } -type Row = { username: string; look: string; value: number }; +type Row = { userId: number; username: string; look: string; value: number }; + +/** + * Users who hid their wallet must not appear in the currency tabs: the profile + * page already honours that, and a leaderboard that ignores it makes the + * setting meaningless. + */ +async function withoutHiddenWallets(rows: Row[]): Promise { + const privacy = await loadProfilePrivacyMap(rows.map((r) => r.userId)); + return rows.filter((r) => privacy.get(r.userId)?.wallet !== false); +} async function loadCreditsRows(): Promise { try { @@ -62,6 +73,7 @@ async function loadCreditsRows(): Promise { () => db .select({ + id: User.id, username: User.username, look: User.look, credits: User.credits, @@ -71,11 +83,14 @@ async function loadCreditsRows(): Promise { .limit(20), { staleMs: 120000 }, ); - return users.map((u) => ({ - username: u.username, - look: u.look, - value: u.credits, - })); + return await withoutHiddenWallets( + users.map((u) => ({ + userId: u.id, + username: u.username, + look: u.look, + value: u.credits, + })), + ); } catch { return []; } @@ -89,6 +104,7 @@ async function loadCurrencyRows(type: number): Promise { () => db .select({ + userId: User.id, username: User.username, look: User.look, value: UsersCurrency.amount, @@ -99,7 +115,7 @@ async function loadCurrencyRows(type: number): Promise { .orderBy(desc(UsersCurrency.amount)) .limit(20), { staleMs: 120000 }, - ); + ).then(withoutHiddenWallets); } catch { return []; } @@ -116,6 +132,7 @@ async function loadSettingsRows( () => db .select({ + userId: User.id, username: User.username, look: User.look, value: column, @@ -166,7 +183,7 @@ export default async function LeaderboardPage({ : null; return ( -
+
)} -
+ ); } diff --git a/src/app/(site)/login/page.tsx b/src/app/(site)/login/page.tsx index 063ba05e..95b61337 100644 --- a/src/app/(site)/login/page.tsx +++ b/src/app/(site)/login/page.tsx @@ -1,4 +1,4 @@ -import { count, desc, eq } from "drizzle-orm"; +import { desc, eq } from "drizzle-orm"; import type { Metadata } from "next"; import { headers } from "next/headers"; import Image from "next/image"; @@ -13,9 +13,11 @@ import { SurfaceCard } from "@/components/surface-card"; import { auth } from "@/lib/auth"; import { safeRedirectPath } from "@/lib/auth/safe-redirect"; import { cached } from "@/lib/cache"; + import { db, User } from "@/lib/db"; import { resolveHotelName } from "@/lib/hotel-name"; import { captchaConfig } from "@/lib/services/captcha"; +import { cachedOnlineCount } from "@/lib/services/public-counters"; import { siteSettings } from "@/lib/services/site-settings"; export async function generateMetadata(): Promise { @@ -34,7 +36,11 @@ export async function generateMetadata(): Promise { export default async function LoginPage({ searchParams, }: { - searchParams: Promise<{ from?: string; registered?: string }>; + searchParams: Promise<{ + from?: string; + registered?: string; + reset?: string; + }>; }) { const t = await getTranslations("pages.login"); const [hotelName, cfg, logo] = await Promise.all([ @@ -53,19 +59,13 @@ export default async function LoginPage({ if (session?.user?.id) redirect(redirectTo); const [online, recentUsers, latestUsers] = await Promise.all([ - cached("online_count", 10_000, () => - db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")) - .then((rows) => rows[0]?.total ?? 0), - ).catch(() => 0), + cachedOnlineCount().catch(() => 0), cached( "auth_online_users", 10_000, () => db - .select({ username: User.username, look: User.look }) + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .where(eq(User.online, "1")) .limit(8), @@ -76,7 +76,7 @@ export default async function LoginPage({ 30_000, () => db - .select({ username: User.username, look: User.look }) + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .orderBy(desc(User.accountCreated)) .limit(8), @@ -96,6 +96,16 @@ export default async function LoginPage({ > {t("registeredSuccess")}

+ ) : sp.reset === "1" ? ( + // `?reset=1` comes from a successful password reset; saying so matters + // because the visitor just changed their password and a silent form + // reads like the reset failed. +

+ {t("passwordChanged")} +

) : undefined; return ( diff --git a/src/app/(site)/logo/page.tsx b/src/app/(site)/logo/page.tsx index dd38b84d..72aafa2c 100644 --- a/src/app/(site)/logo/page.tsx +++ b/src/app/(site)/logo/page.tsx @@ -30,7 +30,7 @@ export default async function LogoPage() { ), ); return ( -
-
+ ); } diff --git a/src/app/(site)/maintenance/page.tsx b/src/app/(site)/maintenance/page.tsx index eecfe2be..ca3f4de1 100644 --- a/src/app/(site)/maintenance/page.tsx +++ b/src/app/(site)/maintenance/page.tsx @@ -14,7 +14,7 @@ export default async function MaintenancePage() { ]); return ( -
+
-
+ ); } diff --git a/src/app/(site)/marketplace/page.tsx b/src/app/(site)/marketplace/page.tsx index 853ada5a..7ca2f601 100644 --- a/src/app/(site)/marketplace/page.tsx +++ b/src/app/(site)/marketplace/page.tsx @@ -82,7 +82,7 @@ export default async function MarketplacePage() { const total = offers.reduce((sum, o) => sum + o.price, 0); return ( -
+
)} -
+ ); } diff --git a/src/app/(site)/me/page.tsx b/src/app/(site)/me/page.tsx index 8b27221a..5018ddf1 100644 --- a/src/app/(site)/me/page.tsx +++ b/src/app/(site)/me/page.tsx @@ -47,14 +47,14 @@ async function MePage({ data = await loadUserDashboard(userId); } catch { return ( -
+

{t("loadError")}

{t("retry")}
-
+ ); } // Daily reward state (settings + schedule + the user's last claim). Never @@ -63,14 +63,14 @@ async function MePage({ const user = data.userRows[0]; if (!user) return ( -
+

{t("loadError")}

{t("login")}
-
+ ); const { hotelName, @@ -145,7 +145,7 @@ async function MePage({ ? error : "error"; return ( -
+
{claimed && (

{t("claimed")} @@ -181,6 +181,8 @@ async function MePage({ width={100} height={140} className={styles.avatar} + loading="eager" + fetchPriority="high" />

{t("welcome", { hotel: hotelName })}

@@ -469,7 +471,7 @@ async function MePage({
-
+ ); } diff --git a/src/app/(site)/messages/page.tsx b/src/app/(site)/messages/page.tsx index d29f8334..0995a702 100644 --- a/src/app/(site)/messages/page.tsx +++ b/src/app/(site)/messages/page.tsx @@ -177,7 +177,7 @@ export default async function MessagesPage({ : null; return ( -
+
{accepted === "1" ? (
{t("success.accepted")} @@ -391,6 +391,6 @@ export default async function MessagesPage({
)} -
+ ); } diff --git a/src/app/(site)/news/[...slug]/page.tsx b/src/app/(site)/news/[...slug]/page.tsx index 396da102..f0d6a743 100644 --- a/src/app/(site)/news/[...slug]/page.tsx +++ b/src/app/(site)/news/[...slug]/page.tsx @@ -94,7 +94,7 @@ async function ArticlePage({ } catch { logger.error("Public article lookup failed", { module: "news" }); return ( -
+

{t("loadError")}

-
+ ); } if (!article) notFound(); @@ -159,7 +159,7 @@ async function ArticlePage({ : null; return ( -
+
{comment === "posted" ? (
{t("success.posted")} @@ -196,7 +196,16 @@ async function ArticlePage({ src={article.image} alt="" decoding="async" - style={{ width: "100%", borderRadius: 10, margin: "0 0 1rem" }} + loading="eager" + // Reserve the box: an unbounded hero image shifts the whole + // article down once the bitmap decodes. + style={{ + width: "100%", + aspectRatio: "16 / 9", + objectFit: "cover", + borderRadius: 10, + margin: "0 0 1rem", + }} /> ) : null} {/* Article body is rich HTML (atom uses TinyMCE) — sanitised server-side. */} @@ -414,7 +423,7 @@ async function ArticlePage({ )}
-
+ ); } diff --git a/src/app/(site)/news/page.tsx b/src/app/(site)/news/page.tsx index d8b506b4..3e8d85e4 100644 --- a/src/app/(site)/news/page.tsx +++ b/src/app/(site)/news/page.tsx @@ -31,7 +31,7 @@ async function NewsPage({ `/news?${new URLSearchParams({ q: result?.search ?? params.q ?? "", order: result?.order ?? "newest", page: String(page) })}`; return ( -
+
@@ -186,7 +186,7 @@ async function NewsPage({ )} -
+ ); } diff --git a/src/app/(site)/page.tsx b/src/app/(site)/page.tsx index 548101ce..640d195a 100644 --- a/src/app/(site)/page.tsx +++ b/src/app/(site)/page.tsx @@ -1,4 +1,4 @@ -import { count, desc, eq } from "drizzle-orm"; +import { desc, eq } from "drizzle-orm"; import { ArrowRight, ChevronDown } from "lucide-react"; import type { Metadata } from "next"; import { headers } from "next/headers"; @@ -25,7 +25,9 @@ import { formatDate } from "@/lib/format-date"; import { resolveHotelName } from "@/lib/hotel-name"; import { captchaConfig } from "@/lib/services/captcha"; import { getNewsList } from "@/lib/services/news-list"; +import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy"; import { + cachedOnlineCount, countArticles, countPhotos, countRooms, @@ -183,13 +185,7 @@ async function getHotelData() { recentUsers, recentPhotos, ] = await Promise.all([ - cached("online_count", 10_000, () => - db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")) - .then((rows) => rows[0]?.total ?? 0), - ).catch(publicReadFailure("home.online")), + cachedOnlineCount().catch(publicReadFailure("home.online")), cached("total_users", 300_000, countUsers, { staleMs: 300000 }).catch( publicReadFailure("home.users"), ), @@ -210,7 +206,7 @@ async function getHotelData() { 15_000, () => db - .select({ username: User.username, look: User.look }) + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .where(eq(User.online, "1")) .limit(12), @@ -259,11 +255,22 @@ export default async function Home() { totalPhotos, articleCount, articles, - recentUsers, + recentUsers: rawRecentUsers, recentPhotos, logo, } = await getHotelData(); + // Users who hide their online state must not surface in the "who is online" + // rails on the homepage either. + const recentUserPrivacy = await loadProfilePrivacyMap( + (rawRecentUsers ?? []).map((u) => u.id), + ); + const recentUsers = + rawRecentUsers === null + ? null + : rawRecentUsers.filter( + (u) => recentUserPrivacy.get(u.id)?.online !== false, + ); const captcha = await captchaConfig(); const nonce = (await headers()).get("x-nonce") ?? undefined; diff --git a/src/app/(site)/photos/page.tsx b/src/app/(site)/photos/page.tsx index 581a2a8d..8dd10b18 100644 --- a/src/app/(site)/photos/page.tsx +++ b/src/app/(site)/photos/page.tsx @@ -10,6 +10,7 @@ import { ContentCard, EmptyState } from "@/components/public/ui"; import { cached } from "@/lib/cache"; import { CameraWeb, db } from "@/lib/db"; import { formatDate } from "@/lib/format-date"; +import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy"; import { publicReadFailure } from "@/lib/services/public-read"; export async function generateMetadata(): Promise { @@ -53,9 +54,16 @@ export default async function PhotosPage() { photos = publicReadFailure("photos")(error); } + // Users can hide their photos everywhere, not only on their profile. + const photoOwners = [...new Set((photos ?? []).map((p) => p.userId))]; + const photoPrivacy = await loadProfilePrivacyMap(photoOwners); + const visiblePhotos = (photos ?? []).filter( + (p) => photoPrivacy.get(p.userId)?.photos !== false, + ); + // Pre-shape for the client lightbox: translate captions server-side so the // client component stays free of i18n/db dependencies. - const items: LightboxPhoto[] = (photos ?? []).map((p) => ({ + const items: LightboxPhoto[] = visiblePhotos.map((p) => ({ id: String(p.id), url: p.url, alt: t("photoAlt", { id: p.userId }), @@ -64,7 +72,7 @@ export default async function PhotosPage() { })); return ( -
+
@@ -76,6 +84,6 @@ export default async function PhotosPage() { )} -
+ ); } diff --git a/src/app/(site)/polls/[id]/page.tsx b/src/app/(site)/polls/[id]/page.tsx index 3c92de01..c23c894b 100644 --- a/src/app/(site)/polls/[id]/page.tsx +++ b/src/app/(site)/polls/[id]/page.tsx @@ -96,7 +96,7 @@ export default async function PollDetailPage({ } return ( -
+

{t("back")}

@@ -248,6 +248,6 @@ export default async function PollDetailPage({
) : null} -
+ ); } diff --git a/src/app/(site)/polls/page.tsx b/src/app/(site)/polls/page.tsx index be741d5d..88b10ee1 100644 --- a/src/app/(site)/polls/page.tsx +++ b/src/app/(site)/polls/page.tsx @@ -60,7 +60,7 @@ export default async function PollsPage() { })); return ( -
+
@@ -122,6 +122,6 @@ export default async function PollsPage() { )} -
+ ); } diff --git a/src/app/(site)/radio/apply/page.tsx b/src/app/(site)/radio/apply/page.tsx index 8a9fae1b..11e77a42 100644 --- a/src/app/(site)/radio/apply/page.tsx +++ b/src/app/(site)/radio/apply/page.tsx @@ -65,7 +65,7 @@ export default async function RadioApplyPage({ : null; return ( -
+
{submitted === "1" ? (
{t("success.submitted")} @@ -199,6 +199,6 @@ export default async function RadioApplyPage({ -
+ ); } diff --git a/src/app/(site)/radio/contests/[id]/page.tsx b/src/app/(site)/radio/contests/[id]/page.tsx index 1a69893c..2da5705a 100644 --- a/src/app/(site)/radio/contests/[id]/page.tsx +++ b/src/app/(site)/radio/contests/[id]/page.tsx @@ -33,7 +33,7 @@ export default async function RadioContestDetailPage({ const active = contest.isActive ? "Active" : "Ended"; return ( -
+

← Back to contests

@@ -90,6 +90,6 @@ export default async function RadioContestDetailPage({ -
+ ); } diff --git a/src/app/(site)/radio/contests/page.tsx b/src/app/(site)/radio/contests/page.tsx index bdbfb02e..fcf9918e 100644 --- a/src/app/(site)/radio/contests/page.tsx +++ b/src/app/(site)/radio/contests/page.tsx @@ -23,7 +23,7 @@ export default async function RadioContestsPage() { .catch(() => []); return ( -
+
@@ -71,6 +71,6 @@ export default async function RadioContestsPage() { )} -
+ ); } diff --git a/src/app/(site)/radio/giveaways/[id]/page.tsx b/src/app/(site)/radio/giveaways/[id]/page.tsx index 42cda4a7..8da0e570 100644 --- a/src/app/(site)/radio/giveaways/[id]/page.tsx +++ b/src/app/(site)/radio/giveaways/[id]/page.tsx @@ -38,7 +38,7 @@ export default async function RadioGiveawayDetailPage({ : null); return ( -
+

← Back to giveaways

@@ -95,6 +95,6 @@ export default async function RadioGiveawayDetailPage({ -
+ ); } diff --git a/src/app/(site)/radio/giveaways/page.tsx b/src/app/(site)/radio/giveaways/page.tsx index e41dab47..e588f451 100644 --- a/src/app/(site)/radio/giveaways/page.tsx +++ b/src/app/(site)/radio/giveaways/page.tsx @@ -25,7 +25,7 @@ export default async function RadioGiveawaysPage() { .catch(() => []); return ( -
+
@@ -78,6 +78,6 @@ export default async function RadioGiveawaysPage() { )} -
+ ); } diff --git a/src/app/(site)/radio/leaderboard/page.tsx b/src/app/(site)/radio/leaderboard/page.tsx index 2ecc2444..3ca9d8dd 100644 --- a/src/app/(site)/radio/leaderboard/page.tsx +++ b/src/app/(site)/radio/leaderboard/page.tsx @@ -38,7 +38,7 @@ export default async function RadioLeaderboardPage() { const rows = await loadRows(); return ( -
+
@@ -85,6 +85,6 @@ export default async function RadioLeaderboardPage() { )} -
+ ); } diff --git a/src/app/(site)/radio/page.tsx b/src/app/(site)/radio/page.tsx index 1aa6511b..8a3f8cc5 100644 --- a/src/app/(site)/radio/page.tsx +++ b/src/app/(site)/radio/page.tsx @@ -120,7 +120,7 @@ export default async function RadioPage() { const isLive = Boolean(streamUrl); return ( -
+
{/* ── Header: live stream + now playing ─────────────────────── */} )} -
+ ); } diff --git a/src/app/(site)/radio/schedule/page.tsx b/src/app/(site)/radio/schedule/page.tsx index c349c04a..417d0456 100644 --- a/src/app/(site)/radio/schedule/page.tsx +++ b/src/app/(site)/radio/schedule/page.tsx @@ -74,7 +74,7 @@ export default async function RadioSchedulePage() { const hasAny = schedules.length > 0; return ( -
+
@@ -126,6 +126,6 @@ export default async function RadioSchedulePage() { )} -
+ ); } diff --git a/src/app/(site)/radio/shouts/page.tsx b/src/app/(site)/radio/shouts/page.tsx index 92b6b573..4e591951 100644 --- a/src/app/(site)/radio/shouts/page.tsx +++ b/src/app/(site)/radio/shouts/page.tsx @@ -73,7 +73,7 @@ export default async function RadioShoutsPage({ : null; return ( -
+
{posted === "1" ? (
{t("success.posted")} @@ -166,6 +166,6 @@ export default async function RadioShoutsPage({
)} -
+ ); } diff --git a/src/app/(site)/rankings/page.tsx b/src/app/(site)/rankings/page.tsx index 4982befb..5eadaffb 100644 --- a/src/app/(site)/rankings/page.tsx +++ b/src/app/(site)/rankings/page.tsx @@ -62,7 +62,7 @@ export default async function RankingsPage() { } return ( -
+
@@ -104,6 +104,6 @@ export default async function RankingsPage() { )} -
+ ); } diff --git a/src/app/(site)/rares/[category]/page.tsx b/src/app/(site)/rares/[category]/page.tsx index b06b65b3..16bc2f9e 100644 --- a/src/app/(site)/rares/[category]/page.tsx +++ b/src/app/(site)/rares/[category]/page.tsx @@ -96,7 +96,7 @@ export default async function RareCategoryPage({ badgeBase && cat.badge ? `${badgeBase}/${cat.badge}.gif` : ""; return ( -
+
)} -
+ ); } diff --git a/src/app/(site)/rares/page.tsx b/src/app/(site)/rares/page.tsx index 747b470b..f3bf3a3a 100644 --- a/src/app/(site)/rares/page.tsx +++ b/src/app/(site)/rares/page.tsx @@ -65,7 +65,7 @@ export default async function RareValuesPage() { } return ( -
+
{categories.length === 0 ? ( @@ -116,6 +116,6 @@ export default async function RareValuesPage() { })} )} -
+ ); } diff --git a/src/app/(site)/redeem/page.tsx b/src/app/(site)/redeem/page.tsx index 1780a8f2..2fff790e 100644 --- a/src/app/(site)/redeem/page.tsx +++ b/src/app/(site)/redeem/page.tsx @@ -29,7 +29,7 @@ export default async function RedeemPage() { if (!user) redirect("/login"); return ( -
+
@@ -63,6 +63,6 @@ export default async function RedeemPage() {

-
+ ); } diff --git a/src/app/(site)/register/page.tsx b/src/app/(site)/register/page.tsx index 3986735e..f23b753f 100644 --- a/src/app/(site)/register/page.tsx +++ b/src/app/(site)/register/page.tsx @@ -1,4 +1,4 @@ -import { count, desc, eq } from "drizzle-orm"; +import { desc, eq } from "drizzle-orm"; import type { Metadata } from "next"; import { headers } from "next/headers"; import Image from "next/image"; @@ -12,9 +12,11 @@ import { RegisterForm } from "@/components/auth/register-form"; import { SurfaceCard } from "@/components/surface-card"; import { auth } from "@/lib/auth"; import { cached } from "@/lib/cache"; + import { db, User } from "@/lib/db"; import { resolveHotelName } from "@/lib/hotel-name"; import { captchaConfig } from "@/lib/services/captcha"; +import { cachedOnlineCount } from "@/lib/services/public-counters"; import { siteSettings } from "@/lib/services/site-settings"; export async function generateMetadata(): Promise { @@ -42,19 +44,13 @@ export default async function RegisterPage() { if (session?.user?.id) redirect("/me"); const [online, recentUsers, latestUsers] = await Promise.all([ - cached("online_count", 10_000, () => - db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")) - .then((rows) => rows[0]?.total ?? 0), - ).catch(() => 0), + cachedOnlineCount().catch(() => 0), cached( "auth_online_users", 10_000, () => db - .select({ username: User.username, look: User.look }) + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .where(eq(User.online, "1")) .limit(8), @@ -65,7 +61,7 @@ export default async function RegisterPage() { 30_000, () => db - .select({ username: User.username, look: User.look }) + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .orderBy(desc(User.accountCreated)) .limit(8), diff --git a/src/app/(site)/reset/page.tsx b/src/app/(site)/reset/page.tsx index 54ac2a5a..d4e7c9a0 100644 --- a/src/app/(site)/reset/page.tsx +++ b/src/app/(site)/reset/page.tsx @@ -1,8 +1,26 @@ +import type { Metadata } from "next"; import { getTranslations } from "next-intl/server"; import { resetPassword } from "@/actions/password-reset"; import Link from "@/components/link"; import { ContentCard } from "@/components/public/ui"; +export async function generateMetadata(): Promise { + const t = await getTranslations("pages.reset"); + return { + title: t("title"), + description: t("subtitle"), + // Single-use links: never indexable. + robots: { index: false, follow: false }, + }; +} + +const ERROR_KEYS: Record = { + password: "passwordMinLength", + ratelimit: "tooManyAttempts", + invalid: "invalidLink", + failed: "failed", +}; + export default async function ResetPage({ searchParams, }: { @@ -10,9 +28,12 @@ export default async function ResetPage({ }) { const t = await getTranslations("pages.reset"); const { email = "", token = "", error } = await searchParams; + // Only codes the action can produce are mapped — anything else stays silent + // instead of being echoed back onto our own domain. + const errorKey = error ? (ERROR_KEYS[error] ?? null) : null; return ( -
+
@@ -28,15 +49,16 @@ export default async function ResetPage({ {t("resetPassword")}
- {error ? ( + {errorKey ? (

- {error} + {t(errorKey)}

) : null}

{t("backToLogin")}

-
+ ); } diff --git a/src/app/(site)/room/[id]/page.tsx b/src/app/(site)/room/[id]/page.tsx index 995e1ad4..42cfe66c 100644 --- a/src/app/(site)/room/[id]/page.tsx +++ b/src/app/(site)/room/[id]/page.tsx @@ -101,7 +101,7 @@ export default async function RoomPage({ .filter(Boolean); return ( -
+

← Back to the hotel @@ -166,6 +166,6 @@ export default async function RoomPage({ Enter the hotel to visit {room.name || `room #${room.id}`} in 3D. -

+ ); } diff --git a/src/app/(site)/search/page.tsx b/src/app/(site)/search/page.tsx index 808d7f08..8422c51f 100644 --- a/src/app/(site)/search/page.tsx +++ b/src/app/(site)/search/page.tsx @@ -5,6 +5,7 @@ import { LocalEventTime } from "@/components/public/local-event-time"; import { ContentCard, EmptyState } from "@/components/public/ui"; import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail"; import { withPublicPagePerformance } from "@/lib/public-page-performance"; +import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy"; import { loadPublicSearch } from "@/lib/services/public-search"; export async function generateMetadata(): Promise { @@ -29,6 +30,11 @@ async function SearchPage({ searchParams }: { searchParams: Promise }) { eventsPage: Number(params.eventsPage ?? 1), }); const query = result?.query ?? ""; + // Users who hide their online state must not have it surfaced here either — + // the listing, not just the profile, is what makes it enumerable. + const userRows = + result?.users.status === "fulfilled" ? result.users.value.rows : []; + const userPrivacy = await loadProfilePrivacyMap(userRows.map((u) => u.id)); const pagination = ( kind: "users" | "rooms" | "news" | "events", data: { page: number; lastPage: number; total: number }, @@ -65,7 +71,7 @@ async function SearchPage({ searchParams }: { searchParams: Promise }) { ); }; return ( -
+
}) { {user.username} - {t(user.online === "1" ? "online" : "offline")} + {t( + user.online === "1" && + userPrivacy.get(user.id)?.online !== false + ? "online" + : "offline", + )} ))} @@ -220,7 +231,7 @@ async function SearchPage({ searchParams }: { searchParams: Promise }) {
)} -
+ ); } diff --git a/src/app/(site)/settings/2fa/page.tsx b/src/app/(site)/settings/2fa/page.tsx index 3a3acbb5..39e3052f 100644 --- a/src/app/(site)/settings/2fa/page.tsx +++ b/src/app/(site)/settings/2fa/page.tsx @@ -73,7 +73,7 @@ export default async function TwoFactorPage({ } return ( -
) : null} + {sp.error === "alreadyenabled" ? ( +

+ {t("alreadyEnabled")} +

+ ) : null} {!hasAppKey ? (

@@ -217,6 +222,6 @@ export default async function TwoFactorPage({ )} -

+ ); } diff --git a/src/app/(site)/settings/sessions/page.tsx b/src/app/(site)/settings/sessions/page.tsx index 4d77c294..d025ff4e 100644 --- a/src/app/(site)/settings/sessions/page.tsx +++ b/src/app/(site)/settings/sessions/page.tsx @@ -78,7 +78,7 @@ export default async function SessionsPage({ } return ( -
+
{signedOutAll === "1" ? (

) : null} -

+ ); } diff --git a/src/app/(site)/shop/page.tsx b/src/app/(site)/shop/page.tsx index 36ab4053..1caa8884 100644 --- a/src/app/(site)/shop/page.tsx +++ b/src/app/(site)/shop/page.tsx @@ -154,7 +154,7 @@ export default async function ShopPage({ : undefined; return ( -
+
{boughtMessage ? (
{boughtMessage} @@ -340,6 +340,6 @@ export default async function ShopPage({
)} -
+ ); } diff --git a/src/app/(site)/shop/topup/page.tsx b/src/app/(site)/shop/topup/page.tsx index b7904b9f..69d855ef 100644 --- a/src/app/(site)/shop/topup/page.tsx +++ b/src/app/(site)/shop/topup/page.tsx @@ -41,7 +41,7 @@ export default async function TopUpPage({ const rate = creditsPerUnit(); return ( -
+
{sp.status === "cancel" ? ( @@ -92,6 +92,6 @@ export default async function TopUpPage({

-
+ ); } diff --git a/src/app/(site)/staff/page.tsx b/src/app/(site)/staff/page.tsx index e6426b71..f80e6258 100644 --- a/src/app/(site)/staff/page.tsx +++ b/src/app/(site)/staff/page.tsx @@ -59,7 +59,7 @@ export default async function StaffPage() { ]); return ( -
+

{t("title")}

@@ -151,6 +151,6 @@ export default async function StaffPage() {
) )} -
+ ); } diff --git a/src/app/(site)/u/[username]/page.tsx b/src/app/(site)/u/[username]/page.tsx index 07d5b619..883f24d9 100644 --- a/src/app/(site)/u/[username]/page.tsx +++ b/src/app/(site)/u/[username]/page.tsx @@ -338,7 +338,7 @@ async function ProfilePage({ const badgeByCode = new Map(badgeDetails.map((b) => [b.badgeKey, b])); return ( -
+
{friend === "sent" ? (
{t("success.sent")} @@ -373,6 +373,8 @@ async function ProfilePage({ width={100} height={150} className={styles.avatar} + loading="eager" + fetchPriority="high" />

{user.username}

@@ -692,7 +694,7 @@ async function ProfilePage({
-
+ ); } diff --git a/src/app/(site)/verify/page.tsx b/src/app/(site)/verify/page.tsx index 8023c2e0..87f9e74e 100644 --- a/src/app/(site)/verify/page.tsx +++ b/src/app/(site)/verify/page.tsx @@ -1,5 +1,6 @@ -import { eq } from "drizzle-orm"; +import { asc, eq } from "drizzle-orm"; import { CheckCircle2, Clock, MailX } from "lucide-react"; +import type { Metadata } from "next"; import { getTranslations } from "next-intl/server"; import { ResendVerificationForm } from "@/components/auth/resend-verification-form"; import Link from "@/components/link"; @@ -7,6 +8,16 @@ import { SurfaceCard } from "@/components/surface-card"; import { isValidVerificationToken } from "@/lib/auth/email-verification"; import { db, User } from "@/lib/db"; +export async function generateMetadata(): Promise { + const t = await getTranslations("pages.verify"); + return { + title: t("verifiedTitle"), + description: t("invalidSubtitle"), + // Token links are single-use; the page itself has nothing to index. + robots: { index: false, follow: false }, + }; +} + type Status = "verified" | "already" | "invalid" | "unavailable"; function StatusCard({ @@ -31,7 +42,7 @@ function StatusCard({ const tint = tintMap[color] ?? tintMap.blue; return ( -
+
-
+ ); } @@ -98,11 +109,14 @@ export default async function VerifyPage({ const ok = await isValidVerificationToken(normalisedEmail, token); if (ok) { try { - const [user] = await db + // Legacy databases allow duplicate addresses; always resolve the + // oldest account so the link cannot verify a different one. + const matches = await db .select({ id: User.id, mailVerified: User.mailVerified }) .from(User) .where(eq(User.mail, normalisedEmail)) - .limit(1); + .orderBy(asc(User.id)); + const user = matches[0]; if (!user) { status = "invalid"; } else if (user.mailVerified === "1") { @@ -173,6 +187,21 @@ export default async function VerifyPage({

{t("unavailableBody")}

+ {/* Transient failure: offer both the retry path and the way out + instead of leaving the visitor stranded on this card. */} + + + {t("backToLogin")} + )} diff --git a/src/app/admin-next/hotel/nitro-cleanup/page.tsx b/src/app/admin-next/hotel/nitro-cleanup/page.tsx index 676d1da4..1458582c 100644 --- a/src/app/admin-next/hotel/nitro-cleanup/page.tsx +++ b/src/app/admin-next/hotel/nitro-cleanup/page.tsx @@ -1,5 +1,11 @@ +import { AdminToaster } from "@/components/admin/admin-toaster"; import { NitroCleanupPanel } from "@/components/admin/studio/nitro-cleanup-panel"; export default function HousekeepingHotelNitroCleanupPage() { - return ; + return ( + <> + + + + ); } diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index 992cce7b..6c101c82 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -6,6 +6,7 @@ import type { ReactNode } from "react"; import { AdminHubChrome } from "@/components/admin/admin-hub-chrome"; import { AdminMobileWrapper } from "@/components/admin/admin-mobile-wrapper"; import { AdminSidebarNav } from "@/components/admin/admin-sidebar-nav"; +import { AdminToaster } from "@/components/admin/admin-toaster"; import { AdminTopbar } from "@/components/admin/admin-topbar"; import { LanguageSwitcher } from "@/components/language-switcher"; import Link from "@/components/link"; @@ -54,6 +55,7 @@ export default async function AdminLayout({ + ); } diff --git a/src/app/admin/logs/_lib/load-ignored-logs.ts b/src/app/admin/logs/_lib/load-ignored-logs.ts index 5476b236..d4586ce3 100644 --- a/src/app/admin/logs/_lib/load-ignored-logs.ts +++ b/src/app/admin/logs/_lib/load-ignored-logs.ts @@ -32,7 +32,8 @@ function parsePageParams( ) { const sp = new URLSearchParams(rawParams); const parsed = parseListParams(sp); - const perPage = Number(rawParams.perPage) || defaultPerPage; + // parseListParams clamps perPage to 1..100 — use it instead of the raw value. + const perPage = parsed.perPage || defaultPerPage; return { search: parsed.search.trim(), page: parsed.page, perPage }; } @@ -63,8 +64,10 @@ async function loadLogList( rawParams, input.defaultPerPage ?? 50, ); - const offset = (page - 1) * perPage; - const like = `%${search}%`; + // Cap the offset: `?page=1000000` otherwise builds a multi-hundred-million + // row scan before returning an empty page. + const offset = Math.min((page - 1) * perPage, 100_000); + const like = `%${search.slice(0, 100)}%`; const where = search ? sql`WHERE ${spec.searchWhere(like)}` : sql``; const [rawRowsResult, countRows] = await Promise.all([ diff --git a/src/app/admin/radio/settings/page.tsx b/src/app/admin/radio/settings/page.tsx index c8e80d76..30f2ff48 100644 --- a/src/app/admin/radio/settings/page.tsx +++ b/src/app/admin/radio/settings/page.tsx @@ -7,7 +7,7 @@ import { StatusCard } from "@/components/admin/dashboard"; import { Button } from "@/components/ui/button"; import { db, WebsiteSetting } from "@/lib/db"; -type Field = { key: string; comment: string }; +type Field = { key: string; comment: string; secret?: boolean }; type Group = { title: string; fields: Field[] }; const GROUPS: Group[] = [ @@ -19,7 +19,11 @@ const GROUPS: Group[] = [ { key: "radio_stream_backup_url", comment: "Backup stream URL" }, { key: "radio_azurecast_base_url", comment: "AzureCast base URL" }, { key: "radio_azurecast_station_id", comment: "AzureCast station ID" }, - { key: "radio_azurecast_api_key", comment: "AzureCast API key" }, + { + key: "radio_azurecast_api_key", + comment: "AzureCast API key", + secret: true, + }, { key: "radio_azurecast_port", comment: "AzureCast stream port" }, { key: "radio_azurecast_protocol", @@ -41,9 +45,14 @@ const GROUPS: Group[] = [ { key: "radio_sambroadcaster_password", comment: "Sambroadcaster password", + secret: true, }, { key: "radio_virtual_dj_url", comment: "Virtual DJ URL" }, - { key: "radio_virtual_dj_password", comment: "Virtual DJ password" }, + { + key: "radio_virtual_dj_password", + comment: "Virtual DJ password", + secret: true, + }, { key: "radio_djs_api_url", comment: "DJs API URL" }, ], }, @@ -331,7 +340,11 @@ const GROUPS: Group[] = [ { title: "Discord webhook & custom code", fields: [ - { key: "radio_discord_webhook_url", comment: "Discord webhook URL" }, + { + key: "radio_discord_webhook_url", + comment: "Discord webhook URL", + secret: true, + }, { key: "radio_discord_enabled", comment: "Enable Discord notifications (0=no, 1=yes)", @@ -467,7 +480,15 @@ export default async function AdminRadioSettingsPage() { {field.comment ? ( diff --git a/src/app/admin/settings/advanced-settings-panel.tsx b/src/app/admin/settings/advanced-settings-panel.tsx index 38116dbf..d732f5d8 100644 --- a/src/app/admin/settings/advanced-settings-panel.tsx +++ b/src/app/admin/settings/advanced-settings-panel.tsx @@ -14,8 +14,10 @@ import { MANAGED_SETTING_KEYS } from "./cms-settings-config"; interface SettingRow { key: string; + /** Masked for secrets — the real value never reaches the client. */ value: string; comment: string | null; + secret?: boolean; } export function AdvancedSettingsPanel({ @@ -126,7 +128,7 @@ export function AdvancedSettingsPanel({ ) : ( - {s.value} + {s.secret ? "•• hidden ••" : s.value} )} diff --git a/src/app/admin/settings/page.tsx b/src/app/admin/settings/page.tsx index 16c6a795..4d8b00f3 100644 --- a/src/app/admin/settings/page.tsx +++ b/src/app/admin/settings/page.tsx @@ -5,6 +5,10 @@ import { getTranslations } from "next-intl/server"; import { AdminPageShell } from "@/components/admin/admin-page-shell"; import { db, WebsiteSetting } from "@/lib/db"; import { canAccess, getAdminContext, PERMS } from "@/lib/permissions"; +import { + isSecretSettingKey, + SECRET_PLACEHOLDER, +} from "@/lib/services/setting-secrets"; import { AdvancedSettingsPanel } from "./advanced-settings-panel"; import { FIELD_DEFAULTS, MANAGED_SETTING_KEYS } from "./cms-settings-config"; import { CmsSettingsForm } from "./cms-settings-form"; @@ -61,10 +65,14 @@ export default async function AdminSettings() { ({ key: s.key, - value: s.value, + value: isSecretSettingKey(s.key) ? SECRET_PLACEHOLDER : s.value, comment: s.comment, + secret: isSecretSettingKey(s.key), }))} canEdit={canEdit} /> diff --git a/src/app/api/admin/import/furni/route.ts b/src/app/api/admin/import/furni/route.ts index d13f785d..332acc83 100644 --- a/src/app/api/admin/import/furni/route.ts +++ b/src/app/api/admin/import/furni/route.ts @@ -5,7 +5,7 @@ import { invalidateCatalogTotals } from "@/features/catalog/server/catalog-total import { apiError, apiOk } from "@/lib/api"; import { withAdmin } from "@/lib/api-handler"; import { db, ItemsBase, queryRows } from "@/lib/db"; -import { normalizeClassname } from "@/lib/furni/classname"; +import { isSafeAssetName, normalizeClassname } from "@/lib/furni/classname"; import { localFurnitureStatus } from "@/lib/furni/local-presence"; import { PERMS } from "@/lib/permissions"; import { logAudit } from "@/lib/services/audit"; @@ -709,9 +709,20 @@ export const PATCH = withAdmin( []; for (const item of items) { - const starIdx = item.classname.indexOf("*"); + const normalised = item.classname.trim(); + // The classname is joined straight into a `.nitro` file path, so a + // separator/looking payload must never get that far. + if (!isSafeAssetName(normalised)) { + results.push({ + classname: item.classname, + ok: false, + warning: "Invalid classname", + }); + continue; + } + const starIdx = normalised.indexOf("*"); const baseClassname = - starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname; + starIdx !== -1 ? normalised.substring(0, starIdx) : normalised; const nitroPath = path.join( /*turbopackIgnore: true*/ nitroDir, `${baseClassname}.nitro`, diff --git a/src/app/api/admin/users/actions/route.ts b/src/app/api/admin/users/actions/route.ts index 551aed09..1256ae33 100644 --- a/src/app/api/admin/users/actions/route.ts +++ b/src/app/api/admin/users/actions/route.ts @@ -6,11 +6,20 @@ import { PERMS } from "@/lib/permissions"; import { rcon } from "@/lib/services/rcon"; import { logStaffActivity } from "@/lib/services/staff-activity"; +/** Currency grants are capped: an unbounded `amount` minted an economy-breaking + * balance with a single request. */ +function positiveAmount(amount: number): boolean { + return Number.isInteger(amount) && amount > 0 && amount <= MAX_CURRENCY_GRANT; +} + +const MAX_CURRENCY_GRANT = 1_000_000; + export const POST = withAdmin( { permission: PERMS.USERS_EDIT }, async (request, context) => { const staffId = context.session.user.id; const staffRank = context.session.user.rank; + const isSuper = context.permissions.isSuperAdmin; const formData = await request.formData(); const userId = Number(formData.get("userId")); const username = String(formData.get("username") || ""); @@ -23,6 +32,33 @@ export const POST = withAdmin( ); } + // Every branch below acts on a live account, so the rank guard that the + // set_rank branch already applies belongs to all of them: staff may not + // act on users at or above their own rank unless they are the hotel's + // dynamic owner. + if (action !== "set_rank") { + const [target] = await db + .select({ rank: User.rank }) + .from(User) + .where(eq(User.id, userId)) + .limit(1); + if (!target) { + return NextResponse.json( + { success: false, message: "User not found" }, + { status: 404 }, + ); + } + if (!isSuper && target.rank >= staffRank) { + return NextResponse.json( + { + success: false, + message: "Cannot act on a user at or above your rank", + }, + { status: 403 }, + ); + } + } + if (action === "set_rank") { const rank = Number(formData.get("rank") || "0"); if (!Number.isInteger(rank) || rank < 1) { @@ -141,7 +177,7 @@ export const POST = withAdmin( if (action === "give_credits") { const credits = Number(formData.get("credits") || "0"); - if (!credits || credits <= 0) { + if (!positiveAmount(credits)) { return NextResponse.json( { success: false, message: "Invalid credit amount" }, { status: 400 }, @@ -166,7 +202,7 @@ export const POST = withAdmin( if (action === "give_duckets") { const amount = Number(formData.get("amount") || "0"); - if (!amount || amount <= 0) { + if (!positiveAmount(amount)) { return NextResponse.json( { success: false, message: "Invalid duckets amount" }, { status: 400 }, @@ -188,7 +224,7 @@ export const POST = withAdmin( if (action === "give_diamonds") { const amount = Number(formData.get("amount") || "0"); - if (!amount || amount <= 0) { + if (!positiveAmount(amount)) { return NextResponse.json( { success: false, message: "Invalid diamonds amount" }, { status: 400 }, @@ -213,7 +249,7 @@ export const POST = withAdmin( if (action === "give_points") { const amount = Number(formData.get("amount") || "0"); - if (!amount || amount <= 0) { + if (!positiveAmount(amount)) { return NextResponse.json( { success: false, message: "Invalid points amount" }, { status: 400 }, diff --git a/src/app/api/diagnostics/errors/route.ts b/src/app/api/diagnostics/errors/route.ts index f14eb07b..f00b2867 100644 --- a/src/app/api/diagnostics/errors/route.ts +++ b/src/app/api/diagnostics/errors/route.ts @@ -23,6 +23,12 @@ export async function POST(request: Request) { !request.headers.get("content-type")?.startsWith("application/json") ) return new Response(null, { status: 403 }); + // The IP bucket is rotatable, so also require the browser's own fetch + // metadata: a script hammering this endpoint from another site is + // `cross-site`, while a real in-page reporter is never. + const fetchSite = request.headers.get("sec-fetch-site"); + if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none") + return new Response(null, { status: 403 }); const limit = await rateLimit(`cms-error:${await clientIp()}`, 20, 60000); if (!limit.ok) return new Response(null, { status: 429 }); const reader = request.body?.getReader(); diff --git a/src/app/api/home/route.ts b/src/app/api/home/route.ts index ec2ea91d..c9c6aa06 100644 --- a/src/app/api/home/route.ts +++ b/src/app/api/home/route.ts @@ -1,11 +1,7 @@ -import { and, count, desc, eq, or, sql } from "drizzle-orm"; import { env } from "@/env"; import { apiJson } from "@/lib/api"; -import { db, User, WebsiteArticles } from "@/lib/db"; -import { resolveHotelName } from "@/lib/hotel-name"; import { logger } from "@/lib/logger"; -import { apiCacheKey, cacheSafe } from "@/lib/redis-cache"; -import { cacheNews } from "@/lib/services/news-cache"; +import { cachedHomePayload } from "@/lib/services/home-payload"; /** * GET /api/home — combined landing payload: the latest 4 website_articles and @@ -14,39 +10,7 @@ import { cacheNews } from "@/lib/services/news-cache"; */ export async function GET(_req: Request) { try { - const data = await cacheNews(apiCacheKey("home"), 15_000, async () => { - const [articles, onlineRows, hotelName] = await Promise.all([ - db - .select({ - id: WebsiteArticles.id, - title: WebsiteArticles.title, - slug: WebsiteArticles.slug, - shortStory: WebsiteArticles.shortStory, - image: WebsiteArticles.image, - createdAt: WebsiteArticles.createdAt, - }) - .from(WebsiteArticles) - .where( - and( - eq(WebsiteArticles.status, "published"), - or( - sql`${WebsiteArticles.publishAt} IS NULL`, - sql`${WebsiteArticles.publishAt} <= NOW()`, - ), - ), - ) - .orderBy(desc(WebsiteArticles.createdAt)) - .limit(4), - db.select({ total: count() }).from(User).where(eq(User.online, "1")), - resolveHotelName(), - ]); - return cacheSafe({ - articles, - online: onlineRows[0]?.total ?? 0, - hotelName, - }); - }); - return apiJson(data); + return apiJson(await cachedHomePayload()); } catch (error) { logger.error("Public news query failed", { module: "news", error }); return apiJson( diff --git a/src/app/api/leaderboard/route.ts b/src/app/api/leaderboard/route.ts index 74db9aa2..ab579ab1 100644 --- a/src/app/api/leaderboard/route.ts +++ b/src/app/api/leaderboard/route.ts @@ -14,11 +14,29 @@ const CURRENCY_TYPE: Record, number> = { duckets: 0, }; -type Row = { rank: number; username: string; look: string; value: number }; +type Row = { + rank: number; + userId: number; + username: string; + look: string; + value: number; +}; + +/** Hidden-wallet users must not be listed, exactly like on the page. */ +async function withoutHiddenWallets( + rows: T[], +): Promise { + const { loadProfilePrivacyMap } = await import( + "@/lib/services/profile-privacy" + ); + const privacy = await loadProfilePrivacyMap(rows.map((r) => r.userId)); + return rows.filter((r) => privacy.get(r.userId)?.wallet !== false); +} async function loadCreditsRows(): Promise { const users = await db .select({ + userId: User.id, username: User.username, look: User.look, credits: User.credits, @@ -26,8 +44,9 @@ async function loadCreditsRows(): Promise { .from(User) .orderBy(desc(User.credits)) .limit(20); - return users.map((u, i) => ({ + return (await withoutHiddenWallets(users)).map((u, i) => ({ rank: i + 1, + userId: u.userId, username: u.username, look: u.look, value: u.credits, @@ -55,15 +74,24 @@ async function loadCurrencyRows(type: number): Promise { top.map((t) => t.userId), ), ); - const byId = new Map(users.map((u) => [u.id, u])); + const allowed = await withoutHiddenWallets(top); + const allowedIds = new Set(allowed.map((t) => t.userId)); + const byId = new Map( + users.filter((u) => allowedIds.has(u.id)).map((u) => [u.id, u]), + ); - return top + return allowed .map((t) => { const u = byId.get(t.userId); if (!u) return null; - return { username: u.username, look: u.look, value: t.amount }; + return { + userId: u.id, + username: u.username, + look: u.look, + value: t.amount, + }; }) - .filter((r): r is Omit => r !== null) + .filter((r) => r !== null) .map((r, i) => ({ rank: i + 1, ...r })); } diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.ts index 1b1c0419..fe1fae3f 100644 --- a/src/app/api/media/route.ts +++ b/src/app/api/media/route.ts @@ -1,13 +1,20 @@ import { existsSync, readdirSync, statSync } from "node:fs"; import { resolve } from "node:path"; -import { NextResponse } from "next/server"; +import { apiOk } from "@/lib/api"; +import { withAdmin } from "@/lib/api-handler"; import { MEDIA_ROOT } from "@/lib/media-storage"; +import { PERMS } from "@/lib/permissions"; -export async function GET() { +/** + * Directory listing for the admin media picker. It used to be world-readable and + * unrated, which handed every visitor a complete inventory of uploaded media + * (logo/favicon paths included) plus their timestamps. + */ +export const GET = withAdmin({ permission: PERMS.PAGES_EDIT }, async () => { const dir = MEDIA_ROOT; // eslint-disable-next-line security/detect-non-literal-fs-filename if (!existsSync(dir)) { - return NextResponse.json({ files: [] }); + return apiOk({ files: [] }); } // eslint-disable-next-line security/detect-non-literal-fs-filename const files = readdirSync(dir) @@ -23,5 +30,5 @@ export async function GET() { }) .sort((a, b) => b.uploaded - a.uploaded); - return NextResponse.json({ files }); -} + return apiOk({ files }); +}); diff --git a/src/app/api/photos/route.ts b/src/app/api/photos/route.ts index 603d0091..923a9b87 100644 --- a/src/app/api/photos/route.ts +++ b/src/app/api/photos/route.ts @@ -31,8 +31,20 @@ export async function GET(req: Request) { .limit(take) .offset(skip), ]); + + // Photo privacy is a per-user setting, so the API honours it like + // the /photos page does. + const { loadProfilePrivacyMap } = await import( + "@/lib/services/profile-privacy" + ); + const photoPrivacy = await loadProfilePrivacyMap( + photos.map((p) => p.userId), + ); + return cacheSafe({ - data: photos, + data: photos.filter( + (p) => photoPrivacy.get(p.userId)?.photos !== false, + ), meta: { page, perPage, diff --git a/src/app/api/radio/shouts/route.ts b/src/app/api/radio/shouts/route.ts index ec904780..ca6276d9 100644 --- a/src/app/api/radio/shouts/route.ts +++ b/src/app/api/radio/shouts/route.ts @@ -4,6 +4,7 @@ import { bearerUserId } from "@/lib/api-auth"; import { db, RadioShouts, User } from "@/lib/db"; import { rateLimit } from "@/lib/rate-limit"; import { apiCacheKey, redisCache } from "@/lib/redis-cache"; +import { moderateOrThrow } from "@/lib/services/moderation"; // Latest 50 radio shouts with their author's username/look resolved. Mirrors the // query behind the public /radio/shouts page (radio_shouts ordered by created_at @@ -93,6 +94,14 @@ export async function POST(req: Request) { ); } + // The same word filter the server action applies — the API path used to + // skip it entirely, so a filtered message could be posted with one fetch. + try { + await moderateOrThrow(message); + } catch (error) { + return apiError((error as Error).message, 422); + } + try { const now = new Date(); await db.insert(RadioShouts).values({ diff --git a/src/app/api/users/[username]/route.ts b/src/app/api/users/[username]/route.ts index 26761409..4f352280 100644 --- a/src/app/api/users/[username]/route.ts +++ b/src/app/api/users/[username]/route.ts @@ -23,6 +23,7 @@ export async function GET( async () => { const [row] = await db .select({ + id: User.id, username: User.username, look: User.look, motto: User.motto, @@ -39,13 +40,21 @@ export async function GET( return null; } + // Wallet / online visibility are per-user settings; the public API + // used to hand both out unconditionally, which made bulk scraping + // of hidden wallets possible. + const { loadProfilePrivacy } = await import( + "@/lib/services/profile-privacy" + ); + const privacy = await loadProfilePrivacy(row.id); + return cacheSafe({ username: row.username, look: row.look, motto: row.motto, rank: row.rank, - credits: row.credits, - online: row.online === "1", + credits: privacy.values.wallet ? row.credits : null, + online: privacy.values.online ? row.online === "1" : null, accountCreated: row.accountCreated, }); }, diff --git a/src/app/client/page.tsx b/src/app/client/page.tsx index 0acdae16..96bf115e 100644 --- a/src/app/client/page.tsx +++ b/src/app/client/page.tsx @@ -1,12 +1,11 @@ -import { count, eq } from "drizzle-orm"; import { headers } from "next/headers"; import { redirect } from "next/navigation"; import { auth } from "@/lib/auth"; import { issueSsoTicket } from "@/lib/auth/sso-ticket"; -import { cached } from "@/lib/cache"; import { resolveClientIp } from "@/lib/client-ip"; -import { db, User } from "@/lib/db"; import { resolveHotelName } from "@/lib/hotel-name"; +import { cachedOnlineCount } from "@/lib/services/public-counters"; + import { siteSettings } from "@/lib/services/site-settings"; import { ClientView } from "./client-view"; @@ -27,13 +26,7 @@ export default async function ClientPage() { // render as fast as possible since the player is waiting for the game. const [ticket, onlineCount] = await Promise.all([ issueSsoTicket(userId, hotelName, ip), - cached("online_count", 10_000, async () => { - const [row] = await db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")); - return row?.total ?? 0; - }).catch(() => 0), + cachedOnlineCount().catch(() => 0), ]); return ( diff --git a/src/app/globals.css b/src/app/globals.css index 8ea10e32..a9bd9afd 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -167,6 +167,61 @@ html { text-size-adjust: 100%; } +/* ── Route transition (CSS only — no animation runtime on public pages) ── */ +@keyframes page-enter-rise { + from { + opacity: 0; + transform: translate3d(0, 10px, 0); + } + to { + opacity: 1; + transform: none; + } +} +.page-enter { + animation: page-enter-rise 240ms ease-out both; +} + +/* ── Route progress indicator ─────────────────────────────────────────── */ +.route-progress { + position: fixed; + inset: 0 0 auto 0; + z-index: 99999; + height: 3px; + overflow: hidden; + background: transparent; + pointer-events: none; + opacity: 0; + transition: opacity 200ms linear; +} +.route-progress[data-loading="true"] { + opacity: 1; +} +@keyframes route-progress-run { + from { + width: 0%; + opacity: 1; + } + 70% { + width: 85%; + opacity: 1; + } + to { + width: 100%; + opacity: 0; + } +} +.route-progress__bar { + display: block; + height: 100%; + width: 0; + background: var(--color-primary); + box-shadow: 0 0 10px var(--color-primary); +} +.route-progress[data-loading="true"] .route-progress__bar { + animation: route-progress-run 400ms ease-in-out both; +} + @media (prefers-reduced-motion: reduce) { html:focus-within { scroll-behavior: auto; diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 1e76b5bd..423d9bb9 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -6,7 +6,6 @@ import { NextIntlClientProvider } from "next-intl"; import { getLocale, getMessages } from "next-intl/server"; import { type ReactNode, Suspense } from "react"; -import { Toaster } from "sonner"; import { GlobalProgressBar } from "@/components/global-progress-bar"; import { PwaRegister } from "@/components/pwa-register"; import { ScopedThemeVars } from "@/components/scoped-theme-vars"; @@ -106,19 +105,6 @@ export default async function RootLayout({ {children} - diff --git a/src/components/admin/admin-toaster.tsx b/src/components/admin/admin-toaster.tsx new file mode 100644 index 00000000..00cc67e0 --- /dev/null +++ b/src/components/admin/admin-toaster.tsx @@ -0,0 +1,23 @@ +import { Toaster } from "sonner"; + +/** + * Toast host for the admin surfaces (the only place `toast()` is used). Kept out + * of the root layout so public pages don't pay for the Sonner bundle. + */ +export function AdminToaster() { + return ( + + ); +} diff --git a/src/components/auth/auth-page-frame.tsx b/src/components/auth/auth-page-frame.tsx index f8110e2c..ca43a01c 100644 --- a/src/components/auth/auth-page-frame.tsx +++ b/src/components/auth/auth-page-frame.tsx @@ -3,9 +3,11 @@ import { AuthTopBar } from "@/components/auth/auth-top-bar"; import { Reveal } from "@/components/motion-reveal"; import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail"; import { SurfaceCard } from "@/components/surface-card"; +import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy"; import { ICON_FRIENDS, ICON_NAV_GOODY, ICON_NAV_ME } from "@/lib/site-icons"; export interface PublicUser { + id: number; username: string; look: string; } @@ -56,22 +58,28 @@ interface AuthUsersCardsProps { * their left column. Cards with no users render nothing, so a cold database * degrades to just the intro panel instead of an empty grid. */ -export function AuthUsersCards({ +export async function AuthUsersCards({ recentUsers, latestUsers, recentTitle, latestTitle, }: AuthUsersCardsProps) { + // "Hide my online status" must hold outside the profile too — the roster is + // exactly where that setting is worth the most. + const privacy = await loadProfilePrivacyMap(recentUsers.map((u) => u.id)); + const onlineUsers = recentUsers.filter( + (u) => privacy.get(u.id)?.online !== false, + ); return ( <> - {recentUsers.length > 0 && ( + {onlineUsers.length > 0 && ( - + )} {latestUsers.length > 0 && ( diff --git a/src/components/global-progress-bar.tsx b/src/components/global-progress-bar.tsx index 8959efaf..85c14323 100644 --- a/src/components/global-progress-bar.tsx +++ b/src/components/global-progress-bar.tsx @@ -1,18 +1,19 @@ "use client"; -import { motion, useIsPresent } from "motion/react"; import { usePathname, useSearchParams } from "next/navigation"; import { useEffect, useState } from "react"; /** - * Global smooth progress indicator for page transitions. - * Uses motion/react for high-performance 60fps animations. + * Global progress indicator for page transitions. + * + * Driven by a CSS class instead of motion/react — the progress bar used to be + * the only reason the masonry-free public layout shipped the whole animation + * runtime to every visitor. Class names come from globals.css (`.route-progress`). */ export function GlobalProgressBar() { const pathname = usePathname(); const searchParams = useSearchParams(); const [isLoading, setIsLoading] = useState(false); - const isPresent = useIsPresent(); // biome-ignore lint/correctness/useExhaustiveDependencies: Route changes intentionally restart the indicator timer. useEffect(() => { @@ -24,17 +25,13 @@ export function GlobalProgressBar() { return () => clearTimeout(timer); }, [pathname, searchParams]); - if (!isLoading && isPresent) return null; - return ( -
- + ); } diff --git a/src/components/mobile-nav-panel.tsx b/src/components/mobile-nav-panel.tsx new file mode 100644 index 00000000..53ea3001 --- /dev/null +++ b/src/components/mobile-nav-panel.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { AnimatePresence, motion } from "motion/react"; +import Image from "next/image"; +import type { ReactNode } from "react"; +import { mobileMenuVariants } from "@/lib/motion"; + +/** + * Animated mobile menu sheet, split out of `MobileNav` so `motion/react` only + * ships once the hamburger menu is opened instead of on every public page. + */ +export default function MobileNavPanel({ + open, + menuId, + menuRef, + brandLabel, + closeLabel, + children, +}: { + open: boolean; + menuId: string; + menuRef: React.RefObject; + brandLabel: string; + closeLabel: string; + children: ReactNode; +}) { + return ( + + {open ? ( + +
+
+ + + {brandLabel} + + + {closeLabel} + +
+ + {children} +
+
+ ) : null} +
+ ); +} diff --git a/src/components/mobile-nav.tsx b/src/components/mobile-nav.tsx index e442f506..8321036f 100644 --- a/src/components/mobile-nav.tsx +++ b/src/components/mobile-nav.tsx @@ -1,7 +1,6 @@ "use client"; -import { AnimatePresence, motion } from "motion/react"; -import Image from "next/image"; +import dynamic from "next/dynamic"; import { type ReactNode, useCallback, @@ -10,7 +9,11 @@ import { useRef, useState, } from "react"; -import { mobileMenuVariants } from "@/lib/motion"; + +/** Lazily loaded so `motion/react` is not in the public pages' initial JS. */ +const MobileNavPanel = dynamic(() => import("@/components/mobile-nav-panel"), { + ssr: false, +}); interface MobileNavProps { children: ReactNode; @@ -129,16 +132,16 @@ export function MobileNav({ aria-haspopup="dialog" aria-controls={menuId} > - + - - {open && ( - -
-
- - - {brandLabel} - - - {closeLabel} - -
- - {children} -
-
- )} -
+ + {children} +
); } diff --git a/src/components/motion-page-wrapper.tsx b/src/components/motion-page-wrapper.tsx index bb40930b..1ac23dac 100644 --- a/src/components/motion-page-wrapper.tsx +++ b/src/components/motion-page-wrapper.tsx @@ -1,10 +1,16 @@ "use client"; -import { AnimatePresence, motion } from "motion/react"; import { usePathname } from "next/navigation"; import type { ReactNode } from "react"; -import { pageTransition } from "@/lib/motion"; +/** + * Route-change entrance animation. + * + * Pure CSS on purpose: the motion/react build this used to pull in cost ~43 KB + * gzip on every public page's initial JS. The animation itself stays identical + * (see `.page-enter` in globals.css), and the global `prefers-reduced-motion` + * block already neutralises it for visitors who ask for less motion. + */ export default function MotionPageWrapper({ children, }: { @@ -13,16 +19,8 @@ export default function MotionPageWrapper({ const pathname = usePathname(); return ( - - - {children} - - +
+ {children} +
); } diff --git a/src/components/nav-dropdown-panel.tsx b/src/components/nav-dropdown-panel.tsx new file mode 100644 index 00000000..bb62207c --- /dev/null +++ b/src/components/nav-dropdown-panel.tsx @@ -0,0 +1,36 @@ +"use client"; + +import { AnimatePresence, motion } from "motion/react"; +import type { ReactNode } from "react"; +import { dropdownVariants } from "@/lib/motion"; + +/** + * Animated body of a nav dropdown. Split out so `motion/react` (~43 KB gzip) + * only ships when a dropdown is actually opened — it used to sit in every + * public page's initial bundle. Loaded client-side only; the closed state is + * rendered by the parent as plain HTML. + */ +export default function NavDropdownPanel({ + open, + children, +}: { + open: boolean; + children: ReactNode; +}) { + return ( + + {open ? ( + + {children} + + ) : null} + + ); +} diff --git a/src/components/nav-dropdown.tsx b/src/components/nav-dropdown.tsx index 03aa2009..28cc89ba 100644 --- a/src/components/nav-dropdown.tsx +++ b/src/components/nav-dropdown.tsx @@ -1,13 +1,23 @@ "use client"; -import { AnimatePresence, motion } from "motion/react"; +import dynamic from "next/dynamic"; import Image from "next/image"; import { type ReactNode, useEffect, useRef, useState } from "react"; -import { dropdownVariants } from "@/lib/motion"; + +/** + * The animated body loads lazily (`motion/react` is ~43 KB gzip and only needed + * while a dropdown is open), so public pages pay nothing until the first + * interaction. + */ +const NavDropdownPanel = dynamic( + () => import("@/components/nav-dropdown-panel"), + { ssr: false }, +); interface NavDropdownProps { label: string; icon?: string; + /** Rendered as a link (default) or a menu item (`as="menu"`). */ children: ReactNode; } @@ -55,13 +65,13 @@ export function NavDropdown({ label, icon, children }: NavDropdownProps) { /> ) : null} {label} - + - - {open && ( - - {children} - - )} - + {/* Closed state is plain HTML; the animation loads on first open. */} + {children} ); } diff --git a/src/components/public/photo-lightbox.tsx b/src/components/public/photo-lightbox.tsx index c5be7891..2ee10b82 100644 --- a/src/components/public/photo-lightbox.tsx +++ b/src/components/public/photo-lightbox.tsx @@ -70,6 +70,8 @@ export function PhotoLightbox({ photos }: { photos: LightboxPhoto[] }) { {p.alt}
diff --git a/src/components/shared/profile-image.tsx b/src/components/shared/profile-image.tsx index 0b2cae0b..c930bd82 100644 --- a/src/components/shared/profile-image.tsx +++ b/src/components/shared/profile-image.tsx @@ -8,6 +8,8 @@ export function ProfileImage({ height, fallback, className, + loading, + fetchPriority, }: { src: string; alt: string; @@ -15,6 +17,9 @@ export function ProfileImage({ height: number; fallback?: string; className?: string; + /** "eager" for the hero image of a page (it *is* the LCP element). */ + loading?: "lazy" | "eager"; + fetchPriority?: "high" | "low" | "auto"; }) { const [failedSrc, setFailedSrc] = useState(null); const failed = failedSrc === src; @@ -43,7 +48,8 @@ export function ProfileImage({ width={width} height={height} className={className} - loading="lazy" + loading={loading ?? "lazy"} + fetchPriority={fetchPriority} decoding="async" onError={() => setFailedSrc(src)} /> diff --git a/src/components/site-header.tsx b/src/components/site-header.tsx index 66fa0a36..31cc4600 100644 --- a/src/components/site-header.tsx +++ b/src/components/site-header.tsx @@ -1,10 +1,8 @@ -import { count, eq } from "drizzle-orm"; import Image from "next/image"; import Link from "@/components/link"; import { LiveOnlineCount } from "@/components/live-online-count"; -import { cached } from "@/lib/cache"; -import { db, User } from "@/lib/db"; import { resolveHotelName } from "@/lib/hotel-name"; +import { cachedOnlineCount } from "@/lib/services/public-counters"; import { siteSettings } from "@/lib/services/site-settings"; export async function SiteHeader() { @@ -16,13 +14,7 @@ export async function SiteHeader() { let online: number; try { - online = await cached("online_count", 10_000, async () => { - const [row] = await db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")); - return row?.total ?? 0; - }); + online = await cachedOnlineCount(); } catch { online = 0; } diff --git a/src/components/top-header.tsx b/src/components/top-header.tsx index 1d7b2093..231aeb6c 100644 --- a/src/components/top-header.tsx +++ b/src/components/top-header.tsx @@ -8,7 +8,6 @@ import Link from "@/components/link"; import { LiveOnlineCount } from "@/components/live-online-count"; import { RoomQuickEntry } from "@/components/room-quick-entry"; import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail"; -import { cached } from "@/lib/cache"; import { db, MessengerFriendrequests, @@ -19,6 +18,7 @@ import { import { resolveHotelName } from "@/lib/hotel-name"; import { canAccess, getApiAdminContext, PERMS } from "@/lib/permissions"; import { logServerError } from "@/lib/server-log"; +import { cachedOnlineCount } from "@/lib/services/public-counters"; function Currency({ icon, @@ -61,31 +61,62 @@ export async function TopHeader({ session }: { session: Session | null }) { let duckets = 0; let diamonds = 0; let look = ""; - try { - const [[user], currencies] = await Promise.all([ - db - .select({ credits: User.credits, look: User.look }) - .from(User) - .where(eq(User.id, id)) - .limit(1), - db - .select({ type: UsersCurrency.type, amount: UsersCurrency.amount }) - .from(UsersCurrency) - .where(eq(UsersCurrency.userId, id)), - ]); - credits = user?.credits ?? 0; - look = user?.look ?? ""; - for (const c of currencies) { + let showAdmin = false; + let showMod = false; + let hotelName = ""; + let online = 0; + let friendRequests: { userFromId: number }[] = []; + let friendRequestUsers: { + id: number; + username: string; + look: string; + }[] = []; + + // One round of queries instead of five sequential ones: the header is on + // every authenticated page, so each extra round-trip is paid on every view. + const [wallet, ctx, name, onlineCount, requests] = await Promise.all([ + (async () => { + try { + const [user, currencies] = await Promise.all([ + db + .select({ credits: User.credits, look: User.look }) + .from(User) + .where(eq(User.id, id)) + .limit(1), + db + .select({ type: UsersCurrency.type, amount: UsersCurrency.amount }) + .from(UsersCurrency) + .where(eq(UsersCurrency.userId, id)), + ]); + return user[0] + ? { credits: user[0].credits, look: user[0].look, currencies } + : null; + } catch (error) { + logServerError("top-header.wallet_failed", error, { userId: id }); + return null; + } + })(), + getApiAdminContext().catch(() => null), + resolveHotelName().catch(() => ""), + cachedOnlineCount().catch((error) => { + logServerError("top-header.online_count_failed", error); + return 0; + }), + db + .select({ userFromId: MessengerFriendrequests.userFromId }) + .from(MessengerFriendrequests) + .where(eq(MessengerFriendrequests.userToId, id)) + .catch(() => [] as { userFromId: number }[]), + ]); + + if (wallet) { + credits = wallet.credits; + look = wallet.look; + for (const c of wallet.currencies) { if (c.type === 0) duckets = c.amount; if (c.type === 5) diamonds = c.amount; } - } catch (error) { - logServerError("top-header.wallet_failed", error, { userId: id }); } - - let showAdmin = false; - let showMod = false; - const ctx = await getApiAdminContext(); if (ctx) { showAdmin = canAccess( ctx.permissions, @@ -102,67 +133,38 @@ export async function TopHeader({ session }: { session: Session | null }) { canAccess(ctx.permissions, PERMS.MOD_CFH_VIEW, ctx.session.user.rank) || canAccess(ctx.permissions, PERMS.MOD_ACTIONS, ctx.session.user.rank); } - const textColor = - "var(--color-navbar-text-readable, var(--color-navbar-text, var(--color-text)))"; - - const hotelName = await resolveHotelName(); - - let online: number; - try { - online = await cached("online_count", 10_000, async () => { - const [row] = await db - .select({ total: count() }) - .from(User) - .where(eq(User.online, "1")); - return row?.total ?? 0; - }); - } catch (error) { - logServerError("top-header.online_count_failed", error); - online = 0; + hotelName = name; + online = onlineCount; + friendRequests = requests; + if (friendRequests.length > 0) { + friendRequestUsers = await db + .select({ id: User.id, username: User.username, look: User.look }) + .from(User) + .where( + inArray( + User.id, + friendRequests.map((r) => r.userFromId), + ), + ) + .catch(() => [] as { id: number; username: string; look: string }[]); } + // The count and the rows are the same question, so derive it from the rows. + const pendingFriendRequests = friendRequests.length; + const textColor = + "var(--color-navbar-text-readable, var(--color-navbar-text, var(--color-text)))"; + // Unread offline messages is the only count we still need on its own. let unreadMessages = 0; - let pendingFriendRequests = 0; try { - const [unreadRows, pendingRows] = await Promise.all([ - db - .select({ total: count() }) - .from(MessengerOffline) - .where(eq(MessengerOffline.userId, id)), - db - .select({ total: count() }) - .from(MessengerFriendrequests) - .where(eq(MessengerFriendrequests.userToId, id)), - ]); - unreadMessages = unreadRows[0]?.total ?? 0; - pendingFriendRequests = pendingRows[0]?.total ?? 0; + const [row] = await db + .select({ total: count() }) + .from(MessengerOffline) + .where(eq(MessengerOffline.userId, id)); + unreadMessages = row?.total ?? 0; } catch (error) { logServerError("top-header.messenger_counts_failed", error, { userId: id }); } - const friendRequests = await db - .select({ userFromId: MessengerFriendrequests.userFromId }) - .from(MessengerFriendrequests) - .where(eq(MessengerFriendrequests.userToId, id)) - .catch(() => [] as { userFromId: number }[]); - - const friendRequestUsers = friendRequests.length - ? await db - .select({ - id: User.id, - username: User.username, - look: User.look, - }) - .from(User) - .where( - inArray( - User.id, - friendRequests.map((r) => r.userFromId), - ), - ) - .catch(() => [] as { id: number; username: string; look: string }[]) - : []; - const totalNotifications = unreadMessages + pendingFriendRequests; return ( diff --git a/src/env.ts b/src/env.ts index 66e45fc9..a45d0e79 100644 --- a/src/env.ts +++ b/src/env.ts @@ -160,6 +160,37 @@ const schema = z path: ["AUTH_SECRET"], }); } + // Mail-enabled deployments must know their own public origin, or every + // verification / password-reset link points at localhost. + const mailEnabled = Boolean( + data.SMTP_HOST || data.RESEND_API_KEY || data.SMTP_USER, + ); + if ( + mailEnabled && + !process.env.APP_URL && + !process.env.NEXT_PUBLIC_APP_URL + ) { + ctx.addIssue({ + code: "custom", + message: + "APP_URL is required when mail is configured — password-reset and email-verification links would otherwise point at localhost", + path: ["APP_URL"], + }); + } + // The two must not disagree: CSRF origin checks and generated links use + // different ones depending on the code path. + if ( + process.env.APP_URL && + process.env.NEXT_PUBLIC_APP_URL && + process.env.APP_URL !== process.env.NEXT_PUBLIC_APP_URL + ) { + ctx.addIssue({ + code: "custom", + message: + "APP_URL and NEXT_PUBLIC_APP_URL must match — links and origin checks disagree", + path: ["NEXT_PUBLIC_APP_URL"], + }); + } // PayPal credentials must be paired. if (data.PAYPAL_CLIENT_ID && !data.PAYPAL_SECRET) { ctx.addIssue({ diff --git a/src/lib/admin-list.ts b/src/lib/admin-list.ts index 46f942eb..1f7b610d 100644 --- a/src/lib/admin-list.ts +++ b/src/lib/admin-list.ts @@ -50,8 +50,10 @@ export async function fetchAdminList( const rawParams = await searchParamsPromise; const sp = new URLSearchParams(rawParams); const parsed = parseListParams(sp); + // `parsed.perPage` is already clamped to 1..100; re-reading the raw value + // here let `?perPage=100000` pass straight into LIMIT. const perPage = config.defaultPerPage - ? Number(rawParams.perPage) || config.defaultPerPage + ? parsed.perPage || config.defaultPerPage : parsed.perPage; const { rows, total } = await config.fetch({ diff --git a/src/lib/api-auth.ts b/src/lib/api-auth.ts index 19e3be94..0d2adcc5 100644 --- a/src/lib/api-auth.ts +++ b/src/lib/api-auth.ts @@ -74,7 +74,21 @@ export async function bearerUserId( } } -/** Mint a new token for a user. Returns the plaintext (shown once). */ +/** + * Mint a new token for a user. Returns the plaintext (shown once). + * + * New tokens get the narrow read/write set every client actually needs. The old + * `abilities: ["*"]` meant a leaked token could call *any* endpoint, including + * destructive ones; the wildcard is kept working for reading old rows so + * existing integrations do not break. + */ +const DEFAULT_TOKEN_ABILITIES: PersonalTokenAbility[] = [ + "radio:read", + "radio:write", + "tickets:read", + "tickets:write", +]; + export async function issueToken( userId: number, name = "api", @@ -86,7 +100,7 @@ export async function issueToken( ...personalTokenScope(userId), name: name.slice(0, 100), token: hashToken(plaintext), - abilities: '["*"]', + abilities: JSON.stringify(DEFAULT_TOKEN_ABILITIES), createdAt: now, updatedAt: now, }); diff --git a/src/lib/auth/session-revocation.ts b/src/lib/auth/session-revocation.ts new file mode 100644 index 00000000..28614191 --- /dev/null +++ b/src/lib/auth/session-revocation.ts @@ -0,0 +1,50 @@ +import { and, eq, sql } from "drizzle-orm"; +import { invalidateJwtVersionCache } from "@/lib/auth/jwt-version-cache"; +import { personalTokenScope } from "@/lib/auth/personal-token-scope"; +import { db, PersonalAccessTokens, User } from "@/lib/db"; +import { logger } from "@/lib/logger"; + +/** + * Kill every live credential for a user: CMS JWTs (by bumping + * `website_jwt_version`, which the `jwt` callback re-checks), the game SSO + * ticket, and the API bearer tokens. + * + * Needed by sign-out-everywhere *and* by every password change: without it, + * resetting a compromised password leaves the attacker's stolen session + * cookie and API token working until they expire on their own. + */ +export async function revokeUserCredentials(userId: number): Promise { + try { + await db + .update(User) + .set({ + websiteJwtVersion: sql`${User.websiteJwtVersion} + 1`, + authTicket: "", + }) + .where(eq(User.id, userId)); + await invalidateJwtVersionCache(userId); + } catch (err) { + logger.warn("Failed to revoke CMS session", { + userId, + error: err instanceof Error ? err.message : "Unknown", + }); + } + + // Revoke API bearer tokens (Sanctum / personal_access_tokens). + try { + const scope = personalTokenScope(userId); + await db + .delete(PersonalAccessTokens) + .where( + and( + eq(PersonalAccessTokens.tokenableId, scope.tokenableId), + eq(PersonalAccessTokens.tokenableType, scope.tokenableType), + ), + ); + } catch (err) { + logger.warn("Failed to revoke personal access tokens", { + userId, + error: err instanceof Error ? err.message : "Unknown", + }); + } +} diff --git a/src/lib/cms-translations.ts b/src/lib/cms-translations.ts index d9fbcd28..c218bced 100644 --- a/src/lib/cms-translations.ts +++ b/src/lib/cms-translations.ts @@ -38,6 +38,40 @@ export class CmsTranslationError extends Error { async function bundled(locale: AppLocale): Promise> { return flattenObject((await import(`../messages/${locale}.json`)).default); } + +/** + * Flattened catalog per locale. The dynamic import is cached by the module + * system, but flattening 6 100 keys is not: doing that on every request cost + * 4–12 ms of CPU per page render. + */ +const flatBundled = new Map>>(); +function bundledFlat(locale: AppLocale): Promise> { + let pending = flatBundled.get(locale); + if (!pending) { + pending = bundled(locale); + flatBundled.set(locale, pending); + } + return pending; +} + +/** Digest of the bundled part of a locale's revision, so only overrides hash. */ +const baseDigest = new Map(); +async function revisionFor( + locale: AppLocale, + overrides: Record, +): Promise { + let digest = baseDigest.get(locale); + if (!digest) { + digest = createHash("sha256") + .update(JSON.stringify(await bundledFlat(locale))) + .digest("hex"); + baseDigest.set(locale, digest); + } + return createHash("sha256") + .update(digest) + .update(JSON.stringify(overrides)) + .digest("hex"); +} async function readOverrides(file: string): Promise> { try { const parsed: unknown = JSON.parse( @@ -65,8 +99,8 @@ export async function readCmsTranslation( root = defaultRoot, ): Promise { const [base, source, overrides] = await Promise.all([ - bundled(locale), - bundled("en"), + bundledFlat(locale), + bundledFlat("en"), readOverrides(localeFile(locale, root)), ]); const messages = { ...base }; @@ -78,9 +112,7 @@ export async function readCmsTranslation( } return { messages, - revision: createHash("sha256") - .update(JSON.stringify([base, overrides])) - .digest("hex"), + revision: await revisionFor(locale, overrides), }; } export async function saveCmsTranslation( @@ -96,8 +128,8 @@ export async function saveCmsTranslation( if (current.revision !== revision) throw new CmsTranslationError("conflict"); const [base, source, overrides] = await Promise.all([ - bundled(locale), - bundled("en"), + bundledFlat(locale), + bundledFlat("en"), readOverrides(file), ]); for (const [key, value] of Object.entries(changes)) { @@ -115,13 +147,54 @@ export async function saveCmsTranslation( return readCmsTranslation(locale, root); }); } -/** Per-request deduplication; runtime edits are visible on the next request. */ +interface MergedMemo { + locale: AppLocale; + mtimeMs: number; + size: number; + builtAt: number; + tree: MessageTree; +} + +/** + * Merged tree per locale, reused across requests until the override file + * changes. Still re-stat'ed (cheap, and at most once per MEMO_TTL_MS) so a + * runtime translation edit stays visible without a restart. + */ +let mergedMemo: MergedMemo | null = null; +const MEMO_TTL_MS = 2_000; + +async function overrideFingerprint( + locale: AppLocale, + root: string, +): Promise<{ mtimeMs: number; size: number }> { + try { + const stat = await fs.stat(localeFile(locale, root)); + return { mtimeMs: stat.mtimeMs, size: stat.size }; + } catch { + return { mtimeMs: 0, size: 0 }; + } +} + +/** Per-request deduplication plus the cross-request memo above. */ export const loadCmsMessages = cache( async (locale: AppLocale): Promise => { + const fingerprint = await overrideFingerprint(locale, defaultRoot); + if ( + mergedMemo && + mergedMemo.locale === locale && + mergedMemo.mtimeMs === fingerprint.mtimeMs && + mergedMemo.size === fingerprint.size && + Date.now() - mergedMemo.builtAt < MEMO_TTL_MS + ) { + return mergedMemo.tree; + } + try { - return unflattenObject( + const tree = unflattenObject( (await readCmsTranslation(locale)).messages, ) as MessageTree; + mergedMemo = { locale, ...fingerprint, builtAt: Date.now(), tree }; + return tree; } catch (error) { logger.error("CMS translation overrides could not be loaded", { locale, diff --git a/src/lib/furni/classname.ts b/src/lib/furni/classname.ts index e3805e69..02c77a33 100644 --- a/src/lib/furni/classname.ts +++ b/src/lib/furni/classname.ts @@ -30,6 +30,23 @@ export function isValidClassname(classname: string): boolean { return CLASSNAME_CHAR_RE.test(classname); } +/** + * Asset-name safety check for values that become file names (swf / nitro / icon). + * + * The real rule is "cannot escape the directory": no path separators, so `../` + * is structurally impossible. Case matters here — classnames in gamedata are + * mixed-case (`recycler_kintsugiB`), so this must not be folded to lowercase the + * way `isValidClassname` presumes. + */ +const ASSET_NAME_RE = /^[\w*.-]+$/; + +export function isSafeAssetName(name: string): boolean { + const trimmed = name.trim(); + if (!trimmed) return false; + if (!ASSET_NAME_RE.test(trimmed)) return false; + return !trimmed.includes(".."); +} + export const LOCAL_ICON_URL_PREFIX = "/swf/dcr/hof_furni/icons/"; export function getLocalIconUrl(classname: string): string { diff --git a/src/lib/permissions.ts b/src/lib/permissions.ts index ca496671..2d164c2b 100644 --- a/src/lib/permissions.ts +++ b/src/lib/permissions.ts @@ -99,6 +99,28 @@ export const loadUserPermissions = cache(async function loadUserPermissions( } }); +/** + * Highest rank the hotel currently has — i.e. who the dynamic owner is. + * Rank comparisons ("can this staff member act on that user") must never be + * hard-coded to a number, because hotels disagree on their top rank. + * Memoised per request so several rank guards in one action cost one query. + */ +export const getHighestRank = cache(async (): Promise => { + const rows = await queryRows<{ + highest_rank: number | bigint | null; + }>(sql` + SELECT COALESCE( + ( + SELECT MAX(u.\`rank\`) + FROM users u + INNER JOIN permission_ranks pr ON pr.id = u.\`rank\` + ), + (SELECT MAX(id) FROM permission_ranks) + ) AS highest_rank + `); + return rows[0]?.highest_rank == null ? null : Number(rows[0].highest_rank); +}); + const getCurrentAuthorizationState = cache(async (userId: number) => resolveAuthorizationState(userId, { user: { @@ -115,26 +137,7 @@ const getCurrentAuthorizationState = cache(async (userId: number) => return row ?? null; }, }, - highestRank: async () => { - // Prefer the highest rank actually held by a user. Unused high IDs in - // permission_ranks (common on Habbo DBs) would otherwise lock the real - // owner out of super-admin / permissions management. - const rows = await queryRows<{ - highest_rank: number | bigint | null; - }>(sql` - SELECT COALESCE( - ( - SELECT MAX(u.\`rank\`) - FROM users u - INNER JOIN permission_ranks pr ON pr.id = u.\`rank\` - ), - (SELECT MAX(id) FROM permission_ranks) - ) AS highest_rank - `); - return rows[0]?.highest_rank == null - ? null - : Number(rows[0].highest_rank); - }, + highestRank: async () => getHighestRank(), }), ); diff --git a/src/lib/proxy-access.ts b/src/lib/proxy-access.ts index a5fbceba..91ce7296 100644 --- a/src/lib/proxy-access.ts +++ b/src/lib/proxy-access.ts @@ -16,3 +16,36 @@ const CACHEABLE_ASSET_PREFIXES = ["/api/imaging/", "/api/media/"]; export function isCacheableAssetPath(pathname: string): boolean { return CACHEABLE_ASSET_PREFIXES.some((prefix) => pathname.startsWith(prefix)); } + +/** + * Public pages whose anonymous rendering barely changes between visitors: + * leaderboards, news, events, staff listing, rankings and the radio schedule. + * These are safe to share at the edge for a few seconds while + * stale-while-revalidate keeps the origin from seeing a stampede. + */ +const EDGE_CACHEABLE_PREFIXES = [ + "/leaderboard", + "/rankings", + "/news", + "/staff", + "/events", + "/radio/schedule", + "/community", + "/rares", + "/shop", + "/badges", + "/developers", + "/help", + "/guilds", +]; + +export function isEdgeCacheablePublicPath(pathname: string): boolean { + if ( + pathname !== "/" && + EDGE_CACHEABLE_PREFIXES.some( + (p) => pathname === p || pathname.startsWith(`${p}/`), + ) + ) + return true; + return false; +} diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts index 2dc5357d..db0b5947 100644 --- a/src/lib/rate-limit.ts +++ b/src/lib/rate-limit.ts @@ -47,12 +47,21 @@ export async function rateLimit( if (redis) { try { const windowKey = `ratelimit:${key}`; - const current = await redis.incr(windowKey); - if (current === 1) await redis.pexpire(windowKey, windowMs); - const ttl = - current === 1 ? windowMs : Math.max(0, await redis.pttl(windowKey)); + // One atomic round trip: INCR + PEXPIRE in a single Lua call. Two + // separate commands left keys without a TTL whenever the process died + // in between, which permanently locked that client out. + const [current, ttl] = (await redis.eval( + `local c = redis.call('INCR', KEYS[1]) + if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end + local t = redis.call('PTTL', KEYS[1]) + if t < 0 then t = tonumber(ARGV[1]) end + return {c, t}`, + 1, + windowKey, + String(windowMs), + )) as [number, number]; if (current > limit) { - return { ok: false, retryAfter: Math.ceil(ttl / 1000) }; + return { ok: false, retryAfter: Math.max(1, Math.ceil(ttl / 1000)) }; } return { ok: true, retryAfter: 0 }; } catch { @@ -64,6 +73,9 @@ export async function rateLimit( ); } } + } else if (redisFailWarned) { + redisFailWarned = false; + logger.info("[rate-limit] Redis available again — shared limits restored."); } cleanup(); diff --git a/src/lib/services/cache-warmup.ts b/src/lib/services/cache-warmup.ts index 2d56a74d..d88c6f9c 100644 --- a/src/lib/services/cache-warmup.ts +++ b/src/lib/services/cache-warmup.ts @@ -2,10 +2,11 @@ import "server-only"; import { asc, desc, eq, gte } from "drizzle-orm"; import { cached } from "@/lib/cache"; -import { db, User, WebsiteTeams } from "@/lib/db"; +import { CameraWeb, db, User, WebsiteTeams } from "@/lib/db"; import { logger } from "@/lib/logger"; import { apiCacheKey, redisCache } from "@/lib/redis-cache"; -import { cacheNews } from "@/lib/services/news-cache"; +import { cachedHomePayload } from "@/lib/services/home-payload"; +import { getNewsList } from "@/lib/services/news-list"; import { countArticles, countOnline, @@ -72,7 +73,7 @@ export async function warmPublicCaches(): Promise { }), ); await warm("online_users", () => - cached("online_users", ONLINE_TTL_MS, listOnlineUsers, { + cached("online_users", ONLINE_TTL_MS, () => listOnlineUsers(100), { staleMs: 15_000, }), ); @@ -82,17 +83,38 @@ export async function warmPublicCaches(): Promise { await warm("api:teams", () => redisCache(apiCacheKey("teams"), 300, loadTeams, { staleMs: 600 }), ); - await warm("news:home", () => - cacheNews(apiCacheKey("home"), 15_000, async () => ({ primed: true })), + // Prime the real payload the route serves — a placeholder here used to be + // cached under the shared key and served to every client after a restart. + await warm("news:home", cachedHomePayload); + await warm("news_list", () => getNewsList(4)); + // The homepage reads its own roster/photo keys, so priming only the counters + // left the first visitor after a deploy paying for the sections anyway. + await warm("home_online_users", () => + cached("home_online_users", 15_000, () => listOnlineUsers(12), { + staleMs: 30_000, + }), + ); + await warm("home_recent_photos", () => + cached("home_recent_photos", 60_000, loadRecentPhotos, { + staleMs: 120_000, + }), ); } -async function listOnlineUsers() { +async function loadRecentPhotos() { return db - .select({ username: User.username, look: User.look }) + .select({ id: CameraWeb.id, url: CameraWeb.url }) + .from(CameraWeb) + .orderBy(desc(CameraWeb.timestamp)) + .limit(4); +} + +async function listOnlineUsers(limit: number) { + return db + .select({ id: User.id, username: User.username, look: User.look }) .from(User) .where(eq(User.online, "1")) - .limit(100); + .limit(limit); } async function loadStaff() { diff --git a/src/lib/services/furni-import.ts b/src/lib/services/furni-import.ts index 768c0fbe..232fa5c3 100644 --- a/src/lib/services/furni-import.ts +++ b/src/lib/services/furni-import.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { and, eq, type SQL, sql } from "drizzle-orm"; import { CatalogPages, db, execResult, ItemsBase, queryRows } from "@/lib/db"; +import { isSafeAssetName } from "@/lib/furni/classname"; import { offerPurchasabilityProblems } from "@/lib/furni/offer-purchasability"; import { officialHabboEnrichmentWarning } from "@/lib/habbo-gamedata-hotel"; import { logger } from "@/lib/logger"; @@ -599,7 +600,6 @@ export async function importSingleFurni(params: { }): Promise { const { id: originalId, - classname, name, description, type, @@ -615,6 +615,16 @@ export async function importSingleFurni(params: { } = params; const warnings: string[] = []; + // A classname becomes a file name below (swf/nitro/icon). It travels from a + // request body into `path.join`, so it must never be able to contain a path + // separator — otherwise a crafted value escapes the asset directories. + const classname = params.classname.trim(); + if (!isSafeAssetName(classname)) { + throw new Error( + `Invalid furniture classname: ${JSON.stringify(params.classname)}`, + ); + } + // Check if already exists by classname OR by spriteId (primary key collision). const [existsByName] = await db .select({ diff --git a/src/lib/services/home-payload.ts b/src/lib/services/home-payload.ts new file mode 100644 index 00000000..3cff7e85 --- /dev/null +++ b/src/lib/services/home-payload.ts @@ -0,0 +1,51 @@ +import "server-only"; + +import { and, count, desc, eq, or, sql } from "drizzle-orm"; +import { db, User, WebsiteArticles } from "@/lib/db"; +import { resolveHotelName } from "@/lib/hotel-name"; +import { apiCacheKey, cacheSafe } from "@/lib/redis-cache"; +import { cacheNews } from "@/lib/services/news-cache"; + +/** + * The `/api/home` landing payload: latest 4 published articles plus the current + * online player count. Shared as a loader so the cache warm-up can prime the + * exact same key the route reads — priming a placeholder instead made every + * instance serve a bogus `{ primed: true }` payload after each restart. + */ +export async function loadHomePayload() { + const [articles, onlineRows, hotelName] = await Promise.all([ + db + .select({ + id: WebsiteArticles.id, + title: WebsiteArticles.title, + slug: WebsiteArticles.slug, + shortStory: WebsiteArticles.shortStory, + image: WebsiteArticles.image, + createdAt: WebsiteArticles.createdAt, + }) + .from(WebsiteArticles) + .where( + and( + eq(WebsiteArticles.status, "published"), + or( + sql`${WebsiteArticles.publishAt} IS NULL`, + sql`${WebsiteArticles.publishAt} <= NOW()`, + ), + ), + ) + .orderBy(desc(WebsiteArticles.createdAt)) + .limit(4), + db.select({ total: count() }).from(User).where(eq(User.online, "1")), + resolveHotelName(), + ]); + return cacheSafe({ + articles, + online: onlineRows[0]?.total ?? 0, + hotelName, + }); +} + +/** Cached read of {@link loadHomePayload} under the route's own key. */ +export async function cachedHomePayload() { + return cacheNews(apiCacheKey("home"), 15_000, loadHomePayload); +} diff --git a/src/lib/services/profile-privacy.ts b/src/lib/services/profile-privacy.ts index 3e9ebe3e..c86c4bab 100644 --- a/src/lib/services/profile-privacy.ts +++ b/src/lib/services/profile-privacy.ts @@ -1,5 +1,5 @@ import "server-only"; -import { eq } from "drizzle-orm"; +import { eq, inArray } from "drizzle-orm"; import { WebsiteProfilePrivacy } from "@/db/profile-privacy"; import { db } from "@/lib/db"; export const profilePrivacyKeys = [ @@ -40,3 +40,64 @@ export async function loadProfilePrivacy(userId: number) { return { values: hiddenProfilePrivacy, unavailable: true }; } } + +function privacyFromRow( + row: Record | undefined, +): ProfilePrivacy { + if (!row) return defaultProfilePrivacy; + return { + wallet: + row.wallet === undefined + ? defaultProfilePrivacy.wallet + : Boolean(row.wallet), + online: + row.online === undefined + ? defaultProfilePrivacy.online + : Boolean(row.online), + friends: + row.friends === undefined + ? defaultProfilePrivacy.friends + : Boolean(row.friends), + photos: + row.photos === undefined + ? defaultProfilePrivacy.photos + : Boolean(row.photos), + registered: + row.registered === undefined + ? defaultProfilePrivacy.registered + : Boolean(row.registered), + }; +} + +/** + * Bulk variant for lists (leaderboard, search, rosters). One query for all ids + * and — exactly like the single-row loader — fails closed: a database error + * returns "hide everything" for every requested user rather than exposing + * wallet balances or online state of unknown visibility. + */ +export async function loadProfilePrivacyMap( + userIds: number[], +): Promise> { + const ids = [...new Set(userIds)].filter( + (id) => Number.isInteger(id) && id > 0, + ); + if (ids.length === 0) return new Map(); + try { + const rows = await db + .select() + .from(WebsiteProfilePrivacy) + .where(inArray(WebsiteProfilePrivacy.userId, ids)); + const map = new Map( + ids.map((id) => [id, defaultProfilePrivacy]), + ); + for (const row of rows) { + map.set( + row.userId, + privacyFromRow(row as unknown as Record), + ); + } + return map; + } catch { + return new Map(ids.map((id) => [id, hiddenProfilePrivacy])); + } +} diff --git a/src/lib/services/public-counters.ts b/src/lib/services/public-counters.ts index b31ef118..9d179268 100644 --- a/src/lib/services/public-counters.ts +++ b/src/lib/services/public-counters.ts @@ -1,6 +1,7 @@ import "server-only"; import { and, count, eq, or, sql } from "drizzle-orm"; +import { cached } from "@/lib/cache"; import { CameraWeb, db, Rooms, User, WebsiteArticles } from "@/lib/db"; /** @@ -73,3 +74,17 @@ export async function countOnline(): Promise { .where(eq(User.online, "1")); return row?.total ?? 0; } + +// ── Shared hot read: online counter ─────────────────────────────────── +// +// One function for every caller (homepage, login, register, headers, the client +// page and the warm-up). Each call site used to inline this, and the ones that +// omitted `staleMs` wrote an entry without a grace window, which made the key +// block on COUNT(*) at every TTL boundary. +export const ONLINE_COUNT_TTL_MS = 10_000; + +export async function cachedOnlineCount(): Promise { + return cached("online_count", ONLINE_COUNT_TTL_MS, countOnline, { + staleMs: 15_000, + }); +} diff --git a/src/lib/services/setting-secrets.ts b/src/lib/services/setting-secrets.ts new file mode 100644 index 00000000..31b33b63 --- /dev/null +++ b/src/lib/services/setting-secrets.ts @@ -0,0 +1,28 @@ +/** Setting keys whose value must never be sent to the browser. */ +const SECRET_SETTING_KEYS = new Set([ + "turnstile_secret", + "recaptcha_secret", + "hcaptcha_secret", + "radio_azurecast_api_key", + "radio_sambroadcaster_password", + "radio_virtual_dj_password", + "radio_discord_webhook_url", + "gitea_token", +]); + +/** + * A key is a secret when it is explicitly listed above, or when its name alone + * says so (`*_secret`, `*_password`, `*_api_key`, ...). Used by the settings UI + * to avoid shipping credentials in the RSC payload, and by the write actions to + * keep "blank means keep the stored value" semantics instead of wiping secrets. + */ +export function isSecretSettingKey(key: string): boolean { + const lower = key.toLowerCase(); + if (SECRET_SETTING_KEYS.has(lower)) return true; + return /(^|_)(secret|password|passwd|token|api_?key|private_?key|credential)$/.test( + lower, + ); +} + +/** Replace a secret with a marker for UI rendering. */ +export const SECRET_PLACEHOLDER = "••••••••"; diff --git a/src/messages/ar.json b/src/messages/ar.json index aa2140a4..f09b417b 100644 --- a/src/messages/ar.json +++ b/src/messages/ar.json @@ -6064,7 +6064,8 @@ "confirm": "Confirm", "enableIntro": "Add a second layer of security with an authenticator app.", "enable": "Enable 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "المصادقة الثنائية مفعلة بالفعل. عطّلها أولاً إذا أردت إعدادها من جديد." }, "login": { "title": "تسجيل الدخول", @@ -6094,7 +6095,8 @@ "showPassword": "إظهار", "hidePassword": "إخفاء", "registeredSuccess": "تم إنشاء الحساب — تحقق من بريدك الوارد للحصول على رابط التحقق، ثم سجّل الدخول.", - "verifyEmailCta": "طلب رابط تحقق جديد" + "verifyEmailCta": "طلب رابط تحقق جديد", + "passwordChanged": "تم تغيير كلمة المرور. سجّل الدخول بكلمة المرور الجديدة." }, "register": { "title": "إنشاء حساب", @@ -6169,7 +6171,8 @@ "emailPlaceholder": "Your email", "sendResetLink": "Send reset link", "backToLogin": "Back to login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "إرسال رابط آخر" }, "reset": { "title": "Set a new password", @@ -6178,7 +6181,9 @@ "resetPassword": "Reset password", "backToLogin": "Back to login", "passwordMinLength": "يجب ألا تقل كلمة المرور عن 12 حرفًا", - "tooManyAttempts": "محاولات كثيرة جدًا — حاول لاحقًا" + "tooManyAttempts": "محاولات كثيرة جدًا — حاول لاحقًا", + "invalidLink": "رابط إعادة التعيين غير صالح أو منتهي الصلاحية. اطلب رابطًا جديدًا.", + "failed": "تعذّرت إعادة تعيين كلمة المرور. حاول مرة أخرى." }, "verify": { "verifiedTitle": "You're all set", diff --git a/src/messages/bg.json b/src/messages/bg.json index fd8d9fbb..37188153 100644 --- a/src/messages/bg.json +++ b/src/messages/bg.json @@ -815,7 +815,8 @@ "confirm": "Потвърдете", "enableIntro": "Добавете втори слой на сигурност с приложение за удостоверяване.", "enable": "Активирайте 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Двуфакторното удостоверяване вече е включено. Изключете го първо, ако искате да го настроите отново." }, "title": "Свързани акаунти", "subtitle": "Свържете социален акаунт, за да влезнете с едно кликване", @@ -849,7 +850,8 @@ "showPassword": "Покажи", "hidePassword": "Скрий", "registeredSuccess": "Акаунтът е създаден — проверете пощата си за връзката за потвърждение и влезете.", - "verifyEmailCta": "Заявка за нова вързка за потвърждение" + "verifyEmailCta": "Заявка за нова вързка за потвърждение", + "passwordChanged": "Паролата ви е променена. Влезте с новата си парола." }, "register": { "title": "Създаване на акаунт", @@ -924,7 +926,8 @@ "emailPlaceholder": "Вашият имейл", "sendResetLink": "Изпратете връзка за нулиране", "backToLogin": "Назад към входа", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Изпрати друг линк" }, "reset": { "title": "Задайте нова парола", @@ -933,7 +936,9 @@ "resetPassword": "Нулирайте паролата", "backToLogin": "Назад към входа", "passwordMinLength": "Паролата трябва да е поне 12 знака", - "tooManyAttempts": "Твърде много опити — опитайте по-късно" + "tooManyAttempts": "Твърде много опити — опитайте по-късно", + "invalidLink": "Този линк за нулиране е невалиден или е изтекъл. Поискайте нов.", + "failed": "Нулирането на паролата не бе успешно. Моля, опитайте отново." }, "verify": { "verifiedTitle": "Всичко е готово", diff --git a/src/messages/cs.json b/src/messages/cs.json index d01b2ddf..011376ef 100644 --- a/src/messages/cs.json +++ b/src/messages/cs.json @@ -815,7 +815,8 @@ "confirm": "Potvrďte", "enableIntro": "Přidejte druhou vrstvu zabezpečení pomocí ověřovací aplikace.", "enable": "Povolit 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Dvoufaktorové ověřování je už zapnuté. Pokud ho chcete nastavit znovu, nejprve ho vypněte." }, "title": "Propojené účty", "subtitle": "Propojte sociální účet a přihlaste se jedním kliknutím", @@ -849,7 +850,8 @@ "showPassword": "Zobrazit", "hidePassword": "Skrýt", "registeredSuccess": "Úter vytvořen — zkontrolujte svou schránku a najděte ověřovací odkaz, poté se přihlaste.", - "verifyEmailCta": "Vyžádat nový ověřovací odkaz" + "verifyEmailCta": "Vyžádat nový ověřovací odkaz", + "passwordChanged": "Vaše heslo bylo změněno. Přihlaste se novým heslem." }, "register": { "title": "Vytvořit účet", @@ -924,7 +926,8 @@ "emailPlaceholder": "Váš email", "sendResetLink": "Odeslat odkaz na reset", "backToLogin": "Zpět k přihlášení", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Odeslat další odkaz" }, "reset": { "title": "Nastavte nové heslo", @@ -933,7 +936,9 @@ "resetPassword": "Obnovit heslo", "backToLogin": "Zpět k přihlášení", "passwordMinLength": "Heslo musí mít alespoň 12 znaků", - "tooManyAttempts": "Příliš mnoho pokusů — zkuste to později" + "tooManyAttempts": "Příliš mnoho pokusů — zkuste to později", + "invalidLink": "Tento odkaz pro obnovu je neplatný nebo vypršel. Vyžádejte si nový.", + "failed": "Heslo nebylo možné obnovit. Zkuste to prosím znovu." }, "verify": { "verifiedTitle": "Vše je připraveno", diff --git a/src/messages/da.json b/src/messages/da.json index f783a046..71cc63d9 100644 --- a/src/messages/da.json +++ b/src/messages/da.json @@ -815,7 +815,8 @@ "confirm": "Bekræft", "enableIntro": "Tilføj et ekstra sikkerhedslag med en godkendelsesapp.", "enable": "Aktiver 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "To-faktor-godkendelse er allerede aktiveret. Deaktivér den først, hvis du vil konfigurere det igen." }, "title": "Linkede konti", "subtitle": "Link en social konto, så du kan logge med et klik", @@ -849,7 +850,8 @@ "showPassword": "Vis", "hidePassword": "Skjul", "registeredSuccess": "Konto oprettet — tjek din indbakke for bekræftelseslinket, og log derefter ind.", - "verifyEmailCta": "Anmod om en ny bekræftelseslink" + "verifyEmailCta": "Anmod om en ny bekræftelseslink", + "passwordChanged": "Din adgangskode er ændret. Log ind med din nye adgangskode." }, "register": { "title": "Opret konto", @@ -924,7 +926,8 @@ "emailPlaceholder": "Din e-mail", "sendResetLink": "Send nulstillingslink", "backToLogin": "Tilbage til login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Send et nyt link" }, "reset": { "title": "Indstil en ny adgangskode", @@ -933,7 +936,9 @@ "resetPassword": "Nulstil adgangskode", "backToLogin": "Tilbage til login", "passwordMinLength": "Adgangskoden skal være på mindst 12 tegn", - "tooManyAttempts": "For mange forsøg — prøv igen senere" + "tooManyAttempts": "For mange forsøg — prøv igen senere", + "invalidLink": "Dette nulstillingslink er ugyldigt eller udløbet. Anmod om et nyt.", + "failed": "Adgangskoden kunne ikke nulstilles. Prøv igen." }, "verify": { "verifiedTitle": "Du er klar", diff --git a/src/messages/de.json b/src/messages/de.json index d9228cad..95ea0bfa 100644 --- a/src/messages/de.json +++ b/src/messages/de.json @@ -785,7 +785,8 @@ "confirm": "Bestätigen", "enableIntro": "Füge eine zweite Sicherheitsebene mit einer Authenticator-App hinzu.", "enable": "2FA aktivieren", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Die Zwei-Faktor-Authentifizierung ist bereits aktiv. Deaktiviere sie zuerst, wenn du sie neu einrichten möchtest." }, "title": "Verknüpfte Konten", "subtitle": "Verknüpfe ein soziales Konto, um mit einem Klick anzumelden", @@ -819,7 +820,8 @@ "showPassword": "Anzeigen", "hidePassword": "Verbergen", "registeredSuccess": "Konto erstellt — prüf dein Postfach für den Bestätigungslink und melde dich dann an.", - "verifyEmailCta": "Neuen Bestätigungslink anfordern" + "verifyEmailCta": "Neuen Bestätigungslink anfordern", + "passwordChanged": "Dein Passwort wurde geändert. Melde dich mit dem neuen Passwort an." }, "register": { "title": "Konto erstellen", @@ -894,7 +896,8 @@ "emailPlaceholder": "Deine E-Mail", "sendResetLink": "Reset-Link senden", "backToLogin": "Zurück zur Anmeldung", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Weiteren Link senden" }, "reset": { "title": "Neues Passwort festlegen", @@ -903,7 +906,9 @@ "resetPassword": "Passwort zurücksetzen", "backToLogin": "Zurück zur Anmeldung", "passwordMinLength": "Das Passwort muss mindestens 12 Zeichen lang sein", - "tooManyAttempts": "Zu viele Versuche — bitte später erneut probieren" + "tooManyAttempts": "Zu viele Versuche — bitte später erneut probieren", + "invalidLink": "Dieser Zurücksetzungslink ist ungültig oder abgelaufen. Fordere einen neuen an.", + "failed": "Das Passwort konnte nicht zurückgesetzt werden. Bitte versuche es erneut." }, "verify": { "verifiedTitle": "Du bist startklar", diff --git a/src/messages/el.json b/src/messages/el.json index 570903b0..83b4168e 100644 --- a/src/messages/el.json +++ b/src/messages/el.json @@ -815,7 +815,8 @@ "confirm": "Επιβεβαίωση", "enableIntro": "Προσθέστε ένα δεύτερο επίπεδο ασφάλειας με μια εφαρμογή ελέγχου ταυτότητας.", "enable": "Ενεργοποίηση 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Η επαλήθευση δύο παραγόντων είναι ήδη ενεργή. Απενεργοποιήστε την πρώτα, αν θέλετε να τη ρυθμίσετε ξανά." }, "title": "Συνδεδεμένοι λογαριασμοί", "subtitle": "Συνδέστε έναν κοινωνικό λογαριασμό για σύνδεση με ένα κλικ", @@ -849,7 +850,8 @@ "showPassword": "Εμφάνιση", "hidePassword": "Απόκρυψη", "registeredSuccess": "Ο λογαριασμός δημιουργήθηκε — ελέγξτε τα εισερχόμενά σας για τον σύνδεσμο επαλήθευσης και συνδεθείτε.", - "verifyEmailCta": "Ζητήστε νέο σύνδεσμο επαλήθευσης" + "verifyEmailCta": "Ζητήστε νέο σύνδεσμο επαλήθευσης", + "passwordChanged": "Ο κωδικός σας άλλαξε. Συνδεθείτε με τον νέο κωδικό." }, "register": { "title": "Δημιουργία λογαριασμού", @@ -924,7 +926,8 @@ "emailPlaceholder": "Το email σας", "sendResetLink": "Αποστολή συνδέσμου επαναφοράς", "backToLogin": "Επιστροφή στην είσοδο", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Αποστολή άλλου συνδέσμου" }, "reset": { "title": "Ορίστε νέο κωδικό πρόσβασης", @@ -933,7 +936,9 @@ "resetPassword": "Επαναφορά κωδικού πρόσβασης", "backToLogin": "Επιστροφή στην είσοδο", "passwordMinLength": "Ο κωδικός πρόσβασης πρέπει να έχει τουλάχιστον 12 χαρακτήρες", - "tooManyAttempts": "Πάρα πολλές προσπάθειες — δοκιμάστε αργότερα" + "tooManyAttempts": "Πάρα πολλές προσπάθειες — δοκιμάστε αργότερα", + "invalidLink": "Αυτός ο σύνδεσμος επαναφοράς δεν είναι έγκυρος ή έχει λήξει. Ζητήστε νέο.", + "failed": "Δεν ήταν δυνατή η επαναφορά του κωδικού. Δοκιμάστε ξανά." }, "verify": { "verifiedTitle": "Είστε έτοιμοι", diff --git a/src/messages/en.json b/src/messages/en.json index 3bf11d98..0f85b668 100644 --- a/src/messages/en.json +++ b/src/messages/en.json @@ -991,7 +991,8 @@ "confirm": "Confirm", "enableIntro": "Add a second layer of security with an authenticator app.", "enable": "Enable 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Two-factor authentication is already enabled. Disable it first if you want to set it up again." }, "login": { "title": "Sign in", @@ -1021,7 +1022,8 @@ "username": "Username", "password": "Password", "registeredSuccess": "Account created — check your inbox for the verification link, then sign in.", - "verifyEmailCta": "Request a new verification link" + "verifyEmailCta": "Request a new verification link", + "passwordChanged": "Your password has been changed. Sign in with your new password." }, "register": { "title": "Create account", @@ -1096,7 +1098,8 @@ "emailPlaceholder": "Your email", "sendResetLink": "Send reset link", "backToLogin": "Back to login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Send another link" }, "reset": { "title": "Set a new password", @@ -1105,7 +1108,9 @@ "resetPassword": "Reset password", "backToLogin": "Back to login", "passwordMinLength": "Password must be at least 12 characters", - "tooManyAttempts": "Too many attempts — try again later" + "tooManyAttempts": "Too many attempts — try again later", + "invalidLink": "This reset link is invalid or has expired. Request a new one.", + "failed": "The password could not be reset. Please try again." }, "verify": { "verifiedTitle": "You're all set", diff --git a/src/messages/es.json b/src/messages/es.json index 37845f62..bdb69363 100644 --- a/src/messages/es.json +++ b/src/messages/es.json @@ -785,7 +785,8 @@ "confirm": "Confirmar", "enableIntro": "Añade una segunda capa de seguridad con una aplicación de autenticación.", "enable": "Activar 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "La verificación en dos pasos ya está activa. Desactívala primero si quieres configurarla otra vez." }, "title": "Cuentas vinculadas", "subtitle": "Vincula una cuenta social para iniciar sesión con un clic", @@ -819,7 +820,8 @@ "showPassword": "Mostrar", "hidePassword": "Ocultar", "registeredSuccess": "Cuenta creada: revisa tu bandeja de entrada para el enlace de verificación e inicia sesión.", - "verifyEmailCta": "Solicitar un nuevo enlace de verificación" + "verifyEmailCta": "Solicitar un nuevo enlace de verificación", + "passwordChanged": "Tu contraseña se ha cambiado. Inicia sesión con la nueva." }, "register": { "title": "Crear cuenta", @@ -894,7 +896,8 @@ "emailPlaceholder": "Tu correo electrónico", "sendResetLink": "Enviar enlace de restablecimiento", "backToLogin": "Volver al inicio de sesión", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Enviar otro enlace" }, "reset": { "title": "Establecer una nueva contraseña", @@ -903,7 +906,9 @@ "resetPassword": "Restablecer contraseña", "backToLogin": "Volver al inicio de sesión", "passwordMinLength": "La contraseña debe tener al menos 12 caracteres", - "tooManyAttempts": "Demasiados intentos — inténtalo más tarde" + "tooManyAttempts": "Demasiados intentos — inténtalo más tarde", + "invalidLink": "Este enlace de restablecimiento no es válido o ha caducado. Solicita uno nuevo.", + "failed": "No se pudo restablecer la contraseña. Vuelve a intentarlo." }, "verify": { "verifiedTitle": "Todo está listo", diff --git a/src/messages/fi.json b/src/messages/fi.json index aeda13d9..f14edf32 100644 --- a/src/messages/fi.json +++ b/src/messages/fi.json @@ -6064,7 +6064,8 @@ "confirm": "Confirm", "enableIntro": "Add a second layer of security with an authenticator app.", "enable": "Enable 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Kaksivaiheinen todennus on jo käytössä. Poista se käytöstä ensin, jos haluat määrittää sen uudelleen." }, "login": { "title": "Kirjaudu sisään", @@ -6094,7 +6095,8 @@ "showPassword": "Näytä", "hidePassword": "Piilota", "registeredSuccess": "Tili luotu — tarkista sähköpostisi ja avaa vahvistuslinkki, sitten kirjaudu sisään.", - "verifyEmailCta": "Pyydä uusi vahvistuslinkki" + "verifyEmailCta": "Pyydä uusi vahvistuslinkki", + "passwordChanged": "Salasanasi on vaihdettu. Kirjaudu uudella salasanalla." }, "register": { "title": "Luo tili", @@ -6169,7 +6171,8 @@ "emailPlaceholder": "Your email", "sendResetLink": "Send reset link", "backToLogin": "Back to login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Lähetä toinen linkki" }, "reset": { "title": "Set a new password", @@ -6178,7 +6181,9 @@ "resetPassword": "Reset password", "backToLogin": "Back to login", "passwordMinLength": "Salasanassa on oltava vähintään 12 merkkiä", - "tooManyAttempts": "Liikaa yrityksiä — yritä myöhemmin uudelleen" + "tooManyAttempts": "Liikaa yrityksiä — yritä myöhemmin uudelleen", + "invalidLink": "Tämä palautuslinkki on virheellinen tai vanhentunut. Pyydä uusi.", + "failed": "Salasanaa ei voitu vaihtaa. Yritä uudelleen." }, "verify": { "verifiedTitle": "You're all set", diff --git a/src/messages/fr.json b/src/messages/fr.json index 0933f1c1..a30c2ca2 100644 --- a/src/messages/fr.json +++ b/src/messages/fr.json @@ -785,7 +785,8 @@ "confirm": "Confirmer", "enableIntro": "Ajoutez une deuxième couche de sécurité avec une application d'authentification.", "enable": "Activer l'A2F", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "La vérification en deux étapes est déjà activée. Désactivez-la d'abord si vous souhaitez la reconfigurer." }, "title": "Comptes liés", "subtitle": "Associez un compte social pour vous connecter en un clic", @@ -819,7 +820,8 @@ "showPassword": "Afficher", "hidePassword": "Masquer", "registeredSuccess": "Compte créé — vérifiez votre boîte mail pour le lien de confirmation, puis connectez-vous.", - "verifyEmailCta": "Demander un nouveau lien de vérification" + "verifyEmailCta": "Demander un nouveau lien de vérification", + "passwordChanged": "Votre mot de passe a été modifié. Connectez-vous avec le nouveau." }, "register": { "title": "Créer un compte", @@ -894,7 +896,8 @@ "emailPlaceholder": "Votre e-mail", "sendResetLink": "Envoyer le lien de réinitialisation", "backToLogin": "Retour à la connexion", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Envoyer un autre lien" }, "reset": { "title": "Définir un nouveau mot de passe", @@ -903,7 +906,9 @@ "resetPassword": "Réinitialiser le mot de passe", "backToLogin": "Retour à la connexion", "passwordMinLength": "Le mot de passe doit contenir au moins 12 caractères", - "tooManyAttempts": "Trop de tentatives — réessayez plus tard" + "tooManyAttempts": "Trop de tentatives — réessayez plus tard", + "invalidLink": "Ce lien de réinitialisation est invalide ou expiré. Demandez-en un nouveau.", + "failed": "Le mot de passe n'a pas pu être réinitialisé. Veuillez réessayer." }, "verify": { "verifiedTitle": "Tout est prêt", diff --git a/src/messages/hr.json b/src/messages/hr.json index 4b93e2a7..b391a53f 100644 --- a/src/messages/hr.json +++ b/src/messages/hr.json @@ -815,7 +815,8 @@ "confirm": "Potvrdi", "enableIntro": "Dodajte drugi sloj sigurnosti pomoću aplikacije za autentifikaciju.", "enable": "Omogućite 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Dvofaktorska autentifikacija je već omogućena. Prvo je onemogućite ako je želite ponovno postaviti." }, "title": "Povezani računi", "subtitle": "Povežite društveni račun za prijavu jednim klikom", @@ -849,7 +850,8 @@ "showPassword": "Prikaži", "hidePassword": "Sakrij", "registeredSuccess": "Račun je stvoren — provjerite poštanski sandučić za poveznicu za verifikaciju, zatim se prijavite.", - "verifyEmailCta": "Zatraži novu poveznicu za verifikaciju" + "verifyEmailCta": "Zatraži novu poveznicu za verifikaciju", + "passwordChanged": "Vaša lozinka je promijenjena. Prijavite se novom lozinkom." }, "register": { "title": "Napravi račun", @@ -924,7 +926,8 @@ "emailPlaceholder": "Vaš email", "sendResetLink": "Pošalji link za resetiranje", "backToLogin": "Natrag na prijavu", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Pošalji drugu poveznicu" }, "reset": { "title": "Postavite novu lozinku", @@ -933,7 +936,9 @@ "resetPassword": "Resetiraj lozinku", "backToLogin": "Natrag na prijavu", "passwordMinLength": "Lozinka mora imati najmanje 12 znakova", - "tooManyAttempts": "Previše pokušaja — pokušajte kasnije" + "tooManyAttempts": "Previše pokušaja — pokušajte kasnije", + "invalidLink": "Ova poveznica za ponovno postavljanje nije valjana ili je istekla. Zatražite novu.", + "failed": "Lozinku nije bilo moguće ponovno postaviti. Pokušajte ponovo." }, "verify": { "verifiedTitle": "Sve je spremno", diff --git a/src/messages/hu.json b/src/messages/hu.json index 8e7f3bc1..2c462569 100644 --- a/src/messages/hu.json +++ b/src/messages/hu.json @@ -815,7 +815,8 @@ "confirm": "Erősítse meg", "enableIntro": "Adjon hozzá egy második biztonsági réteget egy hitelesítő alkalmazással.", "enable": "2FA engedélyezése", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "A kétfaktoros hitelesítés már engedélyezve van. Ha újra szeretné beállítani, először kapcsolja ki." }, "title": "Kapcsolt fiókok", "subtitle": "Kösszön közösségi fiókot egy kattintásos bejelentkezéshez", @@ -849,7 +850,8 @@ "showPassword": "Megjelenítés", "hidePassword": "Elrejtés", "registeredSuccess": "A fiók létrehozva — ellenőrizze a postaládáját a megerősítő linkért, majd jelentkezzen be.", - "verifyEmailCta": "Új megerősítő link kérése" + "verifyEmailCta": "Új megerősítő link kérése", + "passwordChanged": "A jelszava megváltozott. Jelentkezzen be az új jelszavával." }, "register": { "title": "Hozzon létre fiókot", @@ -924,7 +926,8 @@ "emailPlaceholder": "Az Ön email címe", "sendResetLink": "Reset link küldése", "backToLogin": "Vissza a bejelentkezéshez", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Másik link küldése" }, "reset": { "title": "Állítson be új jelszót", @@ -933,7 +936,9 @@ "resetPassword": "Jelszó visszaállítása", "backToLogin": "Vissza a bejelentkezéshez", "passwordMinLength": "A jelszónak legalább 12 karakter hosszúnak kell lennie", - "tooManyAttempts": "Túl sok próbálkozás — próbáld később" + "tooManyAttempts": "Túl sok próbálkozás — próbáld később", + "invalidLink": "Ez a visszaállítási link érvénytelen vagy lejárt. Kérjen újat.", + "failed": "A jelszó visszaállítása nem sikerült. Kérjük, próbálja újra." }, "verify": { "verifiedTitle": "Minden készen áll", diff --git a/src/messages/it.json b/src/messages/it.json index 7b3c66a0..a8990c96 100644 --- a/src/messages/it.json +++ b/src/messages/it.json @@ -957,7 +957,8 @@ "confirm": "Conferma", "enableIntro": "Aggiungi un livello di sicurezza in più con un'app di autenticazione.", "enable": "Attiva 2FA", - "rateLimit": "Troppi tentativi. Attendi prima di riprovare." + "rateLimit": "Troppi tentativi. Attendi prima di riprovare.", + "alreadyEnabled": "La verifica in due passaggi è già attiva. Disattivala prima se vuoi configurarla di nuovo." }, "title": "Account collegati", "subtitle": "Collega un account sociale per accedere con un clic", @@ -991,7 +992,8 @@ "showPassword": "Mostra", "hidePassword": "Nascondi", "registeredSuccess": "Account creato: controlla la tua casella per il link di verifica, poi accedi.", - "verifyEmailCta": "Richiedi un nuovo link di verifica" + "verifyEmailCta": "Richiedi un nuovo link di verifica", + "passwordChanged": "La password è stata cambiata. Accedi con la nuova password." }, "register": { "title": "Crea un account", @@ -1066,7 +1068,8 @@ "emailPlaceholder": "La tua email", "sendResetLink": "Invia link di reset", "backToLogin": "Torna all'accesso", - "errorCaptcha": "Verifica captcha non riuscita. Riprova." + "errorCaptcha": "Verifica captcha non riuscita. Riprova.", + "sendAnotherLink": "Invia un altro link" }, "reset": { "title": "Imposta una nuova password", @@ -1075,7 +1078,9 @@ "resetPassword": "Reimposta password", "backToLogin": "Torna all'accesso", "passwordMinLength": "La password deve contenere almeno 12 caratteri", - "tooManyAttempts": "Troppi tentativi — riprova più tardi" + "tooManyAttempts": "Troppi tentativi — riprova più tardi", + "invalidLink": "Questo link di reimpostazione non è valido o è scaduto. Richiedine uno nuovo.", + "failed": "Non è stato possibile reimpostare la password. Riprova." }, "verify": { "verifiedTitle": "È tutto pronto", diff --git a/src/messages/ja.json b/src/messages/ja.json index d8d2d177..ad27ab90 100644 --- a/src/messages/ja.json +++ b/src/messages/ja.json @@ -6064,7 +6064,8 @@ "confirm": "Confirm", "enableIntro": "Add a second layer of security with an authenticator app.", "enable": "Enable 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "二段階認証はすでに有効です。再度設定するには、まず無効にしてください。" }, "login": { "title": "ログイン", @@ -6094,7 +6095,8 @@ "showPassword": "表示", "hidePassword": "非表示", "registeredSuccess": "アカウントを作成しました。確認用リンクをメールでお確かめのうえ、ログインしてください。", - "verifyEmailCta": "新しい確認リンクをリクエスト" + "verifyEmailCta": "新しい確認リンクをリクエスト", + "passwordChanged": "パスワードを変更しました。新しいパスワードでログインしてください。" }, "register": { "title": "アカウント作成", @@ -6169,7 +6171,8 @@ "emailPlaceholder": "Your email", "sendResetLink": "Send reset link", "backToLogin": "Back to login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "別のリンクを送信" }, "reset": { "title": "Set a new password", @@ -6178,7 +6181,9 @@ "resetPassword": "Reset password", "backToLogin": "Back to login", "passwordMinLength": "パスワードは12文字以上にしてください", - "tooManyAttempts": "試行回数が多すぎます — 後で再度お試しください" + "tooManyAttempts": "試行回数が多すぎます — 後で再度お試しください", + "invalidLink": "このリセットリンクは無効か期限切れです。新しいリンクをリクエストしてください。", + "failed": "パスワードをリセットできませんでした。もう一度お試しください。" }, "verify": { "verifiedTitle": "You're all set", diff --git a/src/messages/nl.json b/src/messages/nl.json index 1bf8ab1b..4c31a514 100644 --- a/src/messages/nl.json +++ b/src/messages/nl.json @@ -987,7 +987,8 @@ "confirm": "Bevestigen", "enableIntro": "Voeg een extra beveiligingslaag toe met een authenticator-app.", "enable": "2FA inschakelen", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Tweestapsverificatie is al ingeschakeld. Schakel het eerst uit als je het opnieuw wilt instellen." }, "title": "Gekoppelde accounts", "subtitle": "Koppel een sociaal account zodat je met één klik kunt inloggen", @@ -1021,7 +1022,8 @@ "username": "Gebruikersnaam", "password": "Wachtwoord", "registeredSuccess": "Account aangemaakt — check je inbox voor de verificatielink en log daarna in.", - "verifyEmailCta": "Een nieuwe verificatielink aanvragen" + "verifyEmailCta": "Een nieuwe verificatielink aanvragen", + "passwordChanged": "Je wachtwoord is gewijzigd. Log in met je nieuwe wachtwoord." }, "register": { "title": "Account aanmaken", @@ -1096,7 +1098,8 @@ "emailPlaceholder": "Je e-mailadres", "sendResetLink": "Resetlink verzenden", "backToLogin": "Terug naar inloggen", - "errorCaptcha": "Captcha-verificatie mislukt. Probeer het opnieuw." + "errorCaptcha": "Captcha-verificatie mislukt. Probeer het opnieuw.", + "sendAnotherLink": "Nog een link versturen" }, "reset": { "title": "Nieuw wachtwoord instellen", @@ -1105,7 +1108,9 @@ "resetPassword": "Wachtwoord resetten", "backToLogin": "Terug naar inloggen", "passwordMinLength": "Wachtwoord moet minimaal 12 tekens lang zijn", - "tooManyAttempts": "Te veel pogingen — probeer het later opnieuw" + "tooManyAttempts": "Te veel pogingen — probeer het later opnieuw", + "invalidLink": "Deze reset-link is ongeldig of verlopen. Vraag een nieuwe aan.", + "failed": "Het wachtwoord kon niet worden gereset. Probeer het opnieuw." }, "verify": { "verifiedTitle": "Je bent helemaal klaar", diff --git a/src/messages/no.json b/src/messages/no.json index e72e5d1f..57021f7c 100644 --- a/src/messages/no.json +++ b/src/messages/no.json @@ -815,7 +815,8 @@ "confirm": "Bekreft", "enableIntro": "Legg til et ekstra lag med sikkerhet med en autentiseringsapp.", "enable": "Aktiver 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Tofaktorautentisering er allerede aktivert. Deaktiver den først hvis du vil sette den opp igjen." }, "title": "Tilknyttede kontoer", "subtitle": "Knytt en sosial konto for å logge inn med ett klikk", @@ -849,7 +850,8 @@ "showPassword": "Vis", "hidePassword": "Skjul", "registeredSuccess": "Konto opprettet — sjekk innboksen for verifiseringslenken, og logg så inn.", - "verifyEmailCta": "Be om en ny verifiseringslenke" + "verifyEmailCta": "Be om en ny verifiseringslenke", + "passwordChanged": "Passordet ditt er endret. Logg inn med det nye passordet." }, "register": { "title": "Opprett konto", @@ -924,7 +926,8 @@ "emailPlaceholder": "Din e-post", "sendResetLink": "Send tilbakestillingslink", "backToLogin": "Tilbake til innlogging", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Send en lenke til" }, "reset": { "title": "Angi et nytt passord", @@ -933,7 +936,9 @@ "resetPassword": "Tilbakestill passord", "backToLogin": "Tilbake til innlogging", "passwordMinLength": "Passordet må være minst 12 tegn", - "tooManyAttempts": "For mange forsøk — prøv igjen senere" + "tooManyAttempts": "For mange forsøk — prøv igjen senere", + "invalidLink": "Denne tilbakestillingslenken er ugyldig eller utløpt. Be om en ny.", + "failed": "Passordet kunne ikke tilbakestilles. Prøv igjen." }, "verify": { "verifiedTitle": "Du er klar", diff --git a/src/messages/pl.json b/src/messages/pl.json index f18a53e4..e4f68048 100644 --- a/src/messages/pl.json +++ b/src/messages/pl.json @@ -815,7 +815,8 @@ "confirm": "Potwierdź", "enableIntro": "Dodaj drugą warstwę zabezpieczeń za pomocą aplikacji uwierzytelniającej.", "enable": "Włącz 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Weryfikacja dwuetapowa jest już włączona. Najpierw ją wyłącz, jeśli chcesz skonfigurować ją ponownie." }, "title": "Połączone konta", "subtitle": "Połącz konto społecznościowe, aby zalogować się jednym kliknięciem", @@ -849,7 +850,8 @@ "showPassword": "Pokaż", "hidePassword": "Ukryj", "registeredSuccess": "Konto utworzone — sprawdź skrzynkę odbiorczą, aby znaleźć link weryfikacyjny, a następnie zaloguj się.", - "verifyEmailCta": "Poproś o nowy link weryfikacyjny" + "verifyEmailCta": "Poproś o nowy link weryfikacyjny", + "passwordChanged": "Twoje hasło zostało zmienione. Zaloguj się nowym hasłem." }, "register": { "title": "Utwórz konto", @@ -924,7 +926,8 @@ "emailPlaceholder": "Twój e-mail", "sendResetLink": "Wyślij link resetujący", "backToLogin": "Powrót do logowania", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Wyślij kolejny link" }, "reset": { "title": "Ustaw nowe hasło", @@ -933,7 +936,9 @@ "resetPassword": "Zresetuj hasło", "backToLogin": "Powrót do logowania", "passwordMinLength": "Hasło musi mieć co najmniej 12 znaków", - "tooManyAttempts": "Zbyt wiele prób — spróbuj później" + "tooManyAttempts": "Zbyt wiele prób — spróbuj później", + "invalidLink": "Ten link resetujący jest nieprawidłowy lub wygasł. Poproś o nowy.", + "failed": "Nie udało się zresetować hasła. Spróbuj ponownie." }, "verify": { "verifiedTitle": "Wszystko gotowe", diff --git a/src/messages/pt.json b/src/messages/pt.json index 9ebec057..4f1a415b 100644 --- a/src/messages/pt.json +++ b/src/messages/pt.json @@ -815,7 +815,8 @@ "confirm": "Confirmar", "enableIntro": "Adicione uma segunda camada de segurança com um aplicativo autenticador.", "enable": "Habilitar 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "A verificação em dois passos já está ativa. Desative-a primeiro se quiser configurá-la novamente." }, "title": "Contas vinculadas", "subtitle": "Vincule uma conta social para iniciar sessão com um clique", @@ -849,7 +850,8 @@ "showPassword": "Mostrar", "hidePassword": "Ocultar", "registeredSuccess": "Conta criada — verifique a sua caixa de entrada para o link de confirmação e inicie sessão.", - "verifyEmailCta": "Pedir um novo link de verificação" + "verifyEmailCta": "Pedir um novo link de verificação", + "passwordChanged": "A sua palavra-passe foi alterada. Inicie sessão com a nova." }, "register": { "title": "Criar conta", @@ -924,7 +926,8 @@ "emailPlaceholder": "Seu e-mail", "sendResetLink": "Enviar link de redefinição", "backToLogin": "Voltar ao login", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Enviar outro link" }, "reset": { "title": "Defina uma nova senha", @@ -933,7 +936,9 @@ "resetPassword": "Redefinir senha", "backToLogin": "Voltar ao login", "passwordMinLength": "A senha deve ter pelo menos 12 caracteres", - "tooManyAttempts": "Muitas tentativas — tente mais tarde" + "tooManyAttempts": "Muitas tentativas — tente mais tarde", + "invalidLink": "Este link de redefinição é inválido ou expirou. Peça um novo.", + "failed": "Não foi possível redefinir a palavra-passe. Tente novamente." }, "verify": { "verifiedTitle": "Você está pronto", diff --git a/src/messages/ro.json b/src/messages/ro.json index ab9d647c..c6543381 100644 --- a/src/messages/ro.json +++ b/src/messages/ro.json @@ -815,7 +815,8 @@ "confirm": "Confirmați", "enableIntro": "Adăugați un al doilea nivel de securitate cu o aplicație de autentificare.", "enable": "Activați 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Autentificarea în doi pași este deja activată. Dezactiveaz-o mai întâi dacă vrei să o configurezi din nou." }, "title": "Conturi conectate", "subtitle": "Conectați un cont social pentru autentificare cu un clic", @@ -849,7 +850,8 @@ "showPassword": "Arată", "hidePassword": "Ascunde", "registeredSuccess": "Cont creat — verifică căsuța pentru linkul de confirmare, apoi autentifică-te.", - "verifyEmailCta": "Solicită un nou link de verificare" + "verifyEmailCta": "Solicită un nou link de verificare", + "passwordChanged": "Parola ta a fost schimbată. Autentifică-te cu noua parolă." }, "register": { "title": "Creați cont", @@ -924,7 +926,8 @@ "emailPlaceholder": "E-mailul dvs", "sendResetLink": "Trimite linkul de resetare", "backToLogin": "Înapoi la autentificare", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Trimite un alt link" }, "reset": { "title": "Setați o nouă parolă", @@ -933,7 +936,9 @@ "resetPassword": "Resetează parola", "backToLogin": "Înapoi la autentificare", "passwordMinLength": "Parola trebuie să aibă cel puțin 12 caractere", - "tooManyAttempts": "Prea multe încercări — încearcă mai târziu" + "tooManyAttempts": "Prea multe încercări — încearcă mai târziu", + "invalidLink": "Acest link de resetare nu este valabil sau a expirat. Solicită unul nou.", + "failed": "Parola nu a putut fi resetată. Încearcă din nou." }, "verify": { "verifiedTitle": "Ești gata", diff --git a/src/messages/ru.json b/src/messages/ru.json index 7982a396..fa7c8eb1 100644 --- a/src/messages/ru.json +++ b/src/messages/ru.json @@ -815,7 +815,8 @@ "confirm": "Подтвердить", "enableIntro": "Добавьте второй уровень безопасности с помощью приложения-аутентификатора.", "enable": "Включить 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Двухфакторная аутентификация уже включена. Сначала отключите её, если хотите настроить заново." }, "title": "Связанные аккаунты", "subtitle": "Свяжите социальный аккаунт для входа одним нажатием", @@ -847,7 +848,8 @@ "showPassword": "Показать", "hidePassword": "Скрыть", "registeredSuccess": "Аккаунт создан — проверьте почту: там ссылка для подтверждения. После этого войдите.", - "verifyEmailCta": "Запросить новую ссылку для подтверждения" + "verifyEmailCta": "Запросить новую ссылку для подтверждения", + "passwordChanged": "Ваш пароль изменён. Войдите с новым паролем." }, "register": { "title": "Создать аккаунт", @@ -922,7 +924,8 @@ "emailPlaceholder": "Ваш адрес электронной почты", "sendResetLink": "Отправить ссылку для сброса", "backToLogin": "Назад к входу", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Отправить другую ссылку" }, "reset": { "title": "Установить новый пароль", @@ -931,7 +934,9 @@ "resetPassword": "Сбросить пароль", "backToLogin": "Назад к входу", "passwordMinLength": "Пароль должен содержать не менее 12 символов", - "tooManyAttempts": "Слишком много попыток — повторите позже" + "tooManyAttempts": "Слишком много попыток — повторите позже", + "invalidLink": "Эта ссылка для сброса недействительна или истекла. Запросите новую.", + "failed": "Не удалось сбросить пароль. Попробуйте снова." }, "verify": { "verifiedTitle": "Всё готово", diff --git a/src/messages/sk.json b/src/messages/sk.json index dc07886b..e6c261dc 100644 --- a/src/messages/sk.json +++ b/src/messages/sk.json @@ -815,7 +815,8 @@ "confirm": "Potvrďte", "enableIntro": "Pridajte druhú vrstvu zabezpečenia pomocou autentifikačnej aplikácie.", "enable": "Povoliť 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Dvojfaktorové overovanie je už zapnuté. Ak ho chcete nastaviť znova, najprv ho vypnite." }, "title": "Prepojené účty", "subtitle": "Prepojte sociálny účet a prihláste sa jedným kliknutím", @@ -849,7 +850,8 @@ "showPassword": "Zobraziť", "hidePassword": "Skryť", "registeredSuccess": "Úter vytvorený — skontrolujte svoju schránku a nájdite overovací odkaz, potom sa prihláste.", - "verifyEmailCta": "Vyžiadať nový overovací odkaz" + "verifyEmailCta": "Vyžiadať nový overovací odkaz", + "passwordChanged": "Vaše heslo bolo zmenené. Prihláste sa novým heslom." }, "register": { "title": "Vytvoriť účet", @@ -924,7 +926,8 @@ "emailPlaceholder": "Váš email", "sendResetLink": "Odoslať odkaz na obnovenie", "backToLogin": "Späť na prihlásenie", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Odoslať ďalší odkaz" }, "reset": { "title": "Nastavte si nové heslo", @@ -933,7 +936,9 @@ "resetPassword": "Obnoviť heslo", "backToLogin": "Späť na prihlásenie", "passwordMinLength": "Heslo musí mať aspoň 12 znakov", - "tooManyAttempts": "Príliš veľa pokusov — skúste to neskôr" + "tooManyAttempts": "Príliš veľa pokusov — skúste to neskôr", + "invalidLink": "Tento odkaz na obnovenie je neplatný alebo vypršal. Vyžiadajte si nový.", + "failed": "Heslo nebolo možné obnoviť. Skúste to znova." }, "verify": { "verifiedTitle": "Všetko je pripravené", diff --git a/src/messages/sr.json b/src/messages/sr.json index 89c38ca2..df6de161 100644 --- a/src/messages/sr.json +++ b/src/messages/sr.json @@ -815,7 +815,8 @@ "confirm": "Потврди", "enableIntro": "Додајте други ниво безбедности помоћу апликације за аутентификацију.", "enable": "Омогући 2ФА", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Двофакторска провера је већ омогућена. Прво је онемогућите ако желите да је поново подесите." }, "title": "Povezani nalozi", "subtitle": "Povežite društveni nalog za prijavu jednim klikom", @@ -849,7 +850,8 @@ "showPassword": "Прикажи", "hidePassword": "Сакриј", "registeredSuccess": "Налог је креиран — проверите пошту за везу за верификацију, а затим се пријавите.", - "verifyEmailCta": "Затражи нову везу за верификацију" + "verifyEmailCta": "Затражи нову везу за верификацију", + "passwordChanged": "Ваша лозинка је промењена. Пријавите се новом лозинком." }, "register": { "title": "Креирајте налог", @@ -924,7 +926,8 @@ "emailPlaceholder": "Ваш емаил", "sendResetLink": "Пошаљи везу за ресетовање", "backToLogin": "Назад на пријаву", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Пошаљи другу везу" }, "reset": { "title": "Поставите нову лозинку", @@ -933,7 +936,9 @@ "resetPassword": "Ресетујте лозинку", "backToLogin": "Назад на пријаву", "passwordMinLength": "Лозинка мора имати најмање 12 знакова", - "tooManyAttempts": "Превише покушаја — покушајте касније" + "tooManyAttempts": "Превише покушаја — покушајте касније", + "invalidLink": "Ова веза за ресетовање није исправна или је истекла. Затражите нову.", + "failed": "Лозинка није могла бити ресетована. Покушајте поново." }, "verify": { "verifiedTitle": "Све је спремно", diff --git a/src/messages/sv.json b/src/messages/sv.json index beef46e7..f3ee6130 100644 --- a/src/messages/sv.json +++ b/src/messages/sv.json @@ -815,7 +815,8 @@ "confirm": "Bekräfta", "enableIntro": "Lägg till ett andra lager av säkerhet med en autentiseringsapp.", "enable": "Aktivera 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Tvåfaktorsverifiering är redan aktiverad. Inaktivera den först om du vill konfigurera den igen." }, "title": "Länkade konton", "subtitle": "Länka ett socialt konto för att logga in med ett klick", @@ -849,7 +850,8 @@ "showPassword": "Visa", "hidePassword": "Dölj", "registeredSuccess": "Konto skapad — kontrollera din inkorg för verifieringslänken och logga sedan in.", - "verifyEmailCta": "Begär en ny verifieringslänk" + "verifyEmailCta": "Begär en ny verifieringslänk", + "passwordChanged": "Ditt lösenord har ändrats. Logga in med ditt nya lösenord." }, "register": { "title": "Skapa konto", @@ -924,7 +926,8 @@ "emailPlaceholder": "Din e-post", "sendResetLink": "Skicka återställningslänk", "backToLogin": "Tillbaka till inloggning", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Skicka en annan länk" }, "reset": { "title": "Ange ett nytt lösenord", @@ -933,7 +936,9 @@ "resetPassword": "Återställ lösenord", "backToLogin": "Tillbaka till inloggning", "passwordMinLength": "Lösenordet måste vara minst 12 tecken", - "tooManyAttempts": "För många försök — försök igen senare" + "tooManyAttempts": "För många försök — försök igen senare", + "invalidLink": "Den här återställningslänken är ogiltig eller har gått ut. Begär en ny.", + "failed": "Lösenordet kunde inte återställas. Försök igen." }, "verify": { "verifiedTitle": "Du är redo", diff --git a/src/messages/tr.json b/src/messages/tr.json index d1c08640..6060ccbc 100644 --- a/src/messages/tr.json +++ b/src/messages/tr.json @@ -815,7 +815,8 @@ "confirm": "Onayla", "enableIntro": "Kimlik doğrulama uygulamasıyla ikinci bir güvenlik katmanı ekleyin.", "enable": "2FA'yı etkinleştir", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "İki adımlı doğrulama zaten etkin. Yeniden kurmak istiyorsanız önce devre dışı bırakın." }, "title": "Bağlı hesaplar", "subtitle": "Tek tıklamayla giriş için sosyal hesap bağlayın", @@ -849,7 +850,8 @@ "showPassword": "Göster", "hidePassword": "Gizle", "registeredSuccess": "Hesap oluşturuldu — doğrulama bağlantısı için gelen kutunuzu kontrol edin, ardından giriş yapın.", - "verifyEmailCta": "Yeni doğrulama bağlantısı iste" + "verifyEmailCta": "Yeni doğrulama bağlantısı iste", + "passwordChanged": "Şifreniz değiştirildi. Yeni şifrenizle giriş yapın." }, "register": { "title": "Hesap oluştur", @@ -924,7 +926,8 @@ "emailPlaceholder": "E-postanız", "sendResetLink": "Sıfırlama bağlantısını gönder", "backToLogin": "Girişe geri dön", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Başka bir bağlantı gönder" }, "reset": { "title": "Yeni bir şifre belirleyin", @@ -933,7 +936,9 @@ "resetPassword": "Şifreyi sıfırla", "backToLogin": "Girişe geri dön", "passwordMinLength": "Şifre en az 12 karakter olmalıdır", - "tooManyAttempts": "Çok fazla deneme — daha sonra tekrar deneyin" + "tooManyAttempts": "Çok fazla deneme — daha sonra tekrar deneyin", + "invalidLink": "Bu şifre sıfırlama bağlantısı geçersiz veya süresi dolmuş. Yeni bir tane isteyin.", + "failed": "Şifre sıfırlanamadı. Lütfen tekrar deneyin." }, "verify": { "verifiedTitle": "Artık hazırsınız", diff --git a/src/messages/uk.json b/src/messages/uk.json index 3b3b43da..d602f737 100644 --- a/src/messages/uk.json +++ b/src/messages/uk.json @@ -815,7 +815,8 @@ "confirm": "Підтвердити", "enableIntro": "Додайте другий рівень безпеки за допомогою програми автентифікації.", "enable": "Увімкніть 2FA", - "rateLimit": "Too many attempts. Please wait before trying again." + "rateLimit": "Too many attempts. Please wait before trying again.", + "alreadyEnabled": "Двофакторна автентифікація вже увімкнена. Спершу вимкніть її, якщо хочете налаштувати знову." }, "title": "Пов'язані акаунти", "subtitle": "Пов'яжіть соціальний акаунт для входу одним натисканням", @@ -849,7 +850,8 @@ "showPassword": "Показати", "hidePassword": "Сховати", "registeredSuccess": "Акаунт створено — перевірте пошту: там посилання для підтвердження. Після цього увійдіть.", - "verifyEmailCta": "Запросити нове посилання для підтвердження" + "verifyEmailCta": "Запросити нове посилання для підтвердження", + "passwordChanged": "Ваш пароль змінено. Увійдіть з новим паролем." }, "register": { "title": "Створити акаунт", @@ -924,7 +926,8 @@ "emailPlaceholder": "Ваш email", "sendResetLink": "Надіслати посилання для скидання", "backToLogin": "Назад до входу", - "errorCaptcha": "Captcha verification failed. Please try again." + "errorCaptcha": "Captcha verification failed. Please try again.", + "sendAnotherLink": "Надіслати інше посилання" }, "reset": { "title": "Встановіть новий пароль", @@ -933,7 +936,9 @@ "resetPassword": "Скинути пароль", "backToLogin": "Назад до входу", "passwordMinLength": "Пароль має містити щонайменше 12 символів", - "tooManyAttempts": "Забагато спроб — спробуйте пізніше" + "tooManyAttempts": "Забагато спроб — спробуйте пізніше", + "invalidLink": "Це посилання для скидання недійсне або прострочене. Запросіть нове.", + "failed": "Не вдалося скинути пароль. Спробуйте ще раз." }, "verify": { "verifiedTitle": "Ви готові", diff --git a/src/proxy.ts b/src/proxy.ts index 0ed7e8f9..522625dd 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -5,6 +5,7 @@ import { buildContentSecurityPolicy, createCspNonce } from "@/lib/csp"; import { ddosReject, enforceDdosRateLimit } from "@/lib/ddos-guard"; import { isCacheableAssetPath, + isEdgeCacheablePublicPath, shouldRedirectAdminRequest, } from "@/lib/proxy-access"; @@ -53,6 +54,11 @@ export const proxy = async (req: import("next/server").NextRequest) => { const headers = new Headers(req.headers); headers.set("x-pathname", pathname); headers.set("x-nonce", nonce); + // Next derives its render nonce from the *request* `content-security-policy` + // header, not from `x-nonce`, so the policy has to travel on the request as + // well — otherwise every inline bootstrap/flight script Next emits ships + // without a nonce and is blocked by the very CSP we are building here. + headers.set("Content-Security-Policy", csp); // A client may supply this legacy derived header; no consumer should trust it. headers.delete("x-real-client-ip"); @@ -65,7 +71,23 @@ export const proxy = async (req: import("next/server").NextRequest) => { // document would reference chunk URLs that no longer exist after a rebuild. // Rendered avatars and uploaded media are immutable per key and already // carry their own long-lived Cache-Control, so they keep it here. - if (!isCacheableAssetPath(pathname)) { + if (isCacheableAssetPath(pathname)) { + // Keep the asset headers as-is. + } else if ( + isEdgeCacheablePublicPath(pathname) && + !req.cookies.get("authjs.session-token") && + !req.cookies.get("__Secure-authjs.session-token") && + !req.nextUrl.searchParams.has("from") + ) { + // Anonymous, low-variance public pages get a short shared cache with + // stale-while-revalidate, so a burst of visitors triggers one render + // instead of one per visitor. Anything session-dependent still falls + // through to the private header below. + response.headers.set( + "Cache-Control", + "public, max-age=0, s-maxage=30, stale-while-revalidate=300", + ); + } else { response.headers.set( "Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate",