P1-P3 admin cleanup: rank guard, SSRF guard, count caching, dead code removal, pagination rewrite

- P1: new src/lib/admin/rank-guard.ts with tryGuardRank/guardRank + RankGuardTarget/Result; extracted from users.ts; applied to admin-bans (create/lift + rank redirect) and admin-badges (caps + rank guard + error surfacing); import-url-safety.ts SSRF guard wired into clone save+icon fetch; logAudit await in help-tickets; antiddos mutations SETTINGS_EDIT; markAllAlertsRead NOTIFICATIONS_EDIT; rankError/saveError in all 25 message files; tests rew/new for bans/badges/rank-guard/import-url-safety

- P2: ticket-inbox merged pagination reworked to single UNION ALL SQL with LIMIT/OFFSET (avoids O(offset) materialization); getCachedAdminCount with cacheFiltered option applied to devops/errors/photos/items/guilds/help-tickets/moderation pages; admin-theme catches→?error=1+banner+25 locales; logger in silent catches (rare-values/writeable-boxes); catalog-items-loader CAST→plain equality; count caching helper extended with opt-in cacheFiltered

- P3: removed dead modules is-staff/notice/recent-furni-resync/log-filters plus load-user-sanctions/user-sanction-timeline; removed orphaned CATALOG_PAGE_COLUMNS re-export; removed getFurniIconUrl from studio-furni-icons

Build: lint 0, typecheck 0, 3480 tests pass, i18n:check exit 0, colors exit 0. Circular chunk warning (9452/10535/66463) is webpack code-splitting artifact; build succeeds.
This commit is contained in:
openhands committed 2026-10-12 17:42:19 +02:00
1 parent 57529fd1ea
commit 7b249a7222
71 files changed
+1031 -1078

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ export async function sendHotelAlert(formData: FormData): Promise<void> {
/** Mark every unread ops alert as read. */
export async function markAllAlertsRead(): Promise<void> {
await requirePermission(PERMS.NOTIFICATIONS_VIEW);
await requirePermission(PERMS.NOTIFICATIONS_EDIT);
try {
await db
.update(AlertLogs)
+5 -5
View File
@@ -140,7 +140,7 @@ async function persistSettings(config: AntiddosConfig): Promise<void> {
* override the proxy reads, so the change is live within the proxy cache TTL.
*/
export async function saveAntiddosSettings(formData: FormData): Promise<void> {
const staff = await requirePermission(PERMS.SETTINGS_VIEW);
const staff = await requirePermission(PERMS.SETTINGS_EDIT);
const config = configFromForm(formData);
try {
@@ -165,7 +165,7 @@ export async function saveAntiddosSettings(formData: FormData): Promise<void> {
* DB-persisted settings. The gate immediately falls back to env ANTI_DDOS_*.
*/
export async function resetAntiddosSettings(): Promise<void> {
const staff = await requirePermission(PERMS.SETTINGS_VIEW);
const staff = await requirePermission(PERMS.SETTINGS_EDIT);
try {
if (redis) await redis.del(OVERRIDE_KEY);
@@ -186,7 +186,7 @@ export async function resetAntiddosSettings(): Promise<void> {
/** Remove a single IP from the temporary DDoS block list. */
export async function unbanAntiddosIp(formData: FormData): Promise<void> {
const staff = await requirePermission(PERMS.SETTINGS_VIEW);
const staff = await requirePermission(PERMS.SETTINGS_EDIT);
const ip = str(formData.get("ip")).trim();
if (!ip) return;
@@ -213,7 +213,7 @@ export async function unbanAntiddosIp(formData: FormData): Promise<void> {
/** Remove an automatic Cloudflare edge block for a tracked IP. */
export async function removeCloudflareRule(formData: FormData): Promise<void> {
const staff = await requirePermission(PERMS.SETTINGS_VIEW);
const staff = await requirePermission(PERMS.SETTINGS_EDIT);
const ip = str(formData.get("ip")).trim();
if (!ip) return;
@@ -233,7 +233,7 @@ export async function removeCloudflareRule(formData: FormData): Promise<void> {
/** Test the configured Cloudflare API credentials against the zone. */
export async function verifyCloudflareConfiguration(): Promise<void> {
const staff = await requirePermission(PERMS.SETTINGS_VIEW);
const staff = await requirePermission(PERMS.SETTINGS_EDIT);
const status = await verifyCloudflareConnection();
await setLastCloudflareVerify(status);
logger.info("Cloudflare API configuration verified", {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+20 -8
View File
@@ -2,8 +2,10 @@
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requirePermissionRateLimited } from "@/lib/admin/guard";
import { Ban, db, User } from "@/lib/db";
import { tryGuardRank } from "@/lib/admin/rank-guard";
import { Ban, db } from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
@@ -26,16 +28,15 @@ export async function createBan(formData: FormData): Promise<void> {
const type = String(formData.get("type"));
if (!(userId > 0) || !BAN_TYPES.has(type)) return;
const guard = await tryGuardRank(userId, staff.rank);
if (!guard.ok && guard.reason === "rank") {
redirect("/admin/bans?error=rank");
}
const now = Math.floor(Date.now() / 1000);
// Emulator convention: banExpire 0 = permanent (not a far-future timestamp).
const banExpire = hours > 0 ? now + Math.floor(hours) * 3600 : 0;
const [user] = await db
.select({ username: User.username })
.from(User)
.where(eq(User.id, userId))
.limit(1);
await db.insert(Ban).values({
userId,
ip: "",
@@ -48,7 +49,7 @@ export async function createBan(formData: FormData): Promise<void> {
cfhTopic: -1,
});
if (user) await rcon.disconnectUser(userId, user.username);
if (guard.ok) await rcon.disconnectUser(userId, guard.target.username);
await logStaffActivity({
staffId: staff.id,
action: "user_ban",
@@ -63,6 +64,17 @@ export async function liftBan(formData: FormData): Promise<void> {
const staff = await requirePermissionRateLimited(PERMS.USERS_BAN);
const id = Number(formData.get("id"));
if (id > 0) {
const [ban] = await db
.select({ userId: Ban.userId })
.from(Ban)
.where(eq(Ban.id, id))
.limit(1);
if (ban) {
const guard = await tryGuardRank(ban.userId, staff.rank);
if (!guard.ok && guard.reason === "rank") {
redirect("/admin/bans?error=rank");
}
}
await db.delete(Ban).where(eq(Ban.id, id));
await logStaffActivity({
staffId: staff.id,
+4 -4
View File
@@ -70,7 +70,7 @@ export const liftBanFromHelpTicket = adminAction(
.where(eq(WebsiteHelpCenterTickets.id, ticketId));
}
logAudit({
await logAudit({
userId: ctx.session.user.id,
action: "unban_via_help_ticket",
target: "User",
@@ -123,7 +123,7 @@ export const replyHelpCenterTicket = adminAction(
.where(eq(WebsiteHelpCenterTickets.id, ticketId));
});
logAudit({
await logAudit({
userId: staffId,
action: "help_center_ticket_reply",
target: "WebsiteHelpCenterTickets",
@@ -157,7 +157,7 @@ export const closeHelpCenterTicket = adminAction(
.set({ open: false, updatedAt: now })
.where(eq(WebsiteHelpCenterTickets.id, ticketId));
logAudit({
await logAudit({
userId: Number(ctx.session.user.id),
action: "help_center_ticket_close",
target: "WebsiteHelpCenterTickets",
@@ -193,7 +193,7 @@ export const reopenHelpCenterTicket = adminAction(
.set({ open: true, updatedAt: now })
.where(eq(WebsiteHelpCenterTickets.id, ticketId));
logAudit({
await logAudit({
userId: Number(ctx.session.user.id),
action: "help_center_ticket_reopen",
target: "WebsiteHelpCenterTickets",
+14 -12
View File
@@ -6,6 +6,7 @@ import { requirePermission } from "@/lib/admin/guard";
import { db, WebsiteRareValueCategories, WebsiteRareValues } from "@/lib/db";
import { EDGE_CACHE_TAGS, purgeEdgeCache } from "@/lib/edge-cache";
import { formPositiveBigInt } from "@/lib/form-data";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
export async function createCategory(formData: FormData): Promise<void> {
@@ -31,8 +32,9 @@ export async function createCategory(formData: FormData): Promise<void> {
badge,
priority,
});
} catch {
// Unique name collision or DB error — ignore, page will re-render unchanged.
} catch (err) {
// Unique name collision or DB error — page re-renders unchanged.
logger.error("Failed to create rare-value category", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
@@ -51,8 +53,8 @@ export async function deleteCategory(formData: FormData): Promise<void> {
await db
.delete(WebsiteRareValueCategories)
.where(eq(WebsiteRareValueCategories.id, id));
} catch {
// Not found or DB error — ignore.
} catch (err) {
logger.error("Failed to delete rare value", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
@@ -100,8 +102,8 @@ export async function createValue(formData: FormData): Promise<void> {
currencyType,
furnitureIcon,
});
} catch {
// DB error — ignore.
} catch (err) {
logger.error("Failed to persist rare value", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
@@ -114,8 +116,8 @@ export async function deleteValue(formData: FormData): Promise<void> {
try {
await db.delete(WebsiteRareValues).where(eq(WebsiteRareValues.id, id));
} catch {
// Not found or DB error — ignore.
} catch (err) {
logger.error("Failed to delete rare value", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
@@ -146,8 +148,8 @@ export async function updateCategory(formData: FormData): Promise<void> {
.update(WebsiteRareValueCategories)
.set({ name, badge, priority })
.where(eq(WebsiteRareValueCategories.id, id));
} catch {
// Unique name collision or DB error — ignore.
} catch (err) {
logger.error("Failed to update rare-value category", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
@@ -201,8 +203,8 @@ export async function updateValue(formData: FormData): Promise<void> {
.update(WebsiteRareValues)
.set(sets)
.where(eq(WebsiteRareValues.id, id));
} catch {
// DB error — ignore.
} catch (err) {
logger.error("Failed to persist rare value", { err });
}
revalidatePath("/admin/rare-values");
void purgeEdgeCache([EDGE_CACHE_TAGS.public], "rare values edited");
+12 -12
View File
@@ -141,13 +141,13 @@ describe("saveTheme", () => {
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?saved=1");
});
it("fails soft when a write fails and still redirects", async () => {
it("redirects with an error when a write fails", async () => {
fakeDbConfig.fail = (kind: string) => kind === "insert";
await saveTheme(form({ color_primary: "#123456" }));
expect(mockReload).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
expect(mockRevalidatePath).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?saved=1");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
@@ -182,12 +182,12 @@ describe("applyPreset", () => {
expect(mockLogStaffActivity).not.toHaveBeenCalled();
});
it("fails soft on write errors", async () => {
it("redirects with an error on write errors", async () => {
fakeDbConfig.fail = (kind: string) => kind === "insert";
await applyPreset(form({ preset: "Ocean" }));
expect(mockReload).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?preset=Ocean");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
@@ -218,12 +218,12 @@ describe("saveCustomTheme", () => {
expect(mockSnapshotCurrentTheme).not.toHaveBeenCalled();
});
it("fails soft on persist errors", async () => {
it("redirects with an error on persist errors", async () => {
mockUpsertCustomTheme.mockRejectedValueOnce(new Error("store down"));
await saveCustomTheme(form({ name: "My Theme" }));
expect(mockLogStaffActivity).not.toHaveBeenCalled();
expect(mockRevalidatePath).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?savedTheme=1");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
@@ -284,7 +284,7 @@ describe("applyCustomTheme", () => {
);
});
it("fails soft on write errors", async () => {
it("redirects with an error on write errors", async () => {
mockGetCustomTheme.mockResolvedValue({
id: "t1",
name: "Studio",
@@ -296,7 +296,7 @@ describe("applyCustomTheme", () => {
expect(mockReload).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
expect(mockRevalidatePath).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?theme=Studio");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
@@ -324,11 +324,11 @@ describe("renameCustomTheme", () => {
expect(mockSnapshotCurrentTheme).not.toHaveBeenCalled();
});
it("fails soft on upsert errors", async () => {
it("redirects with an error on upsert errors", async () => {
mockUpsertCustomTheme.mockRejectedValueOnce(new Error("store down"));
await renameCustomTheme(form({ id: "t1", name: "Renamed" }));
expect(mockRevalidatePath).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?renamed=1");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
@@ -350,10 +350,10 @@ describe("deleteCustomTheme", () => {
expect(mockDeleteCustomThemeStore).not.toHaveBeenCalled();
});
it("fails soft on store errors", async () => {
it("redirects with an error on store errors", async () => {
mockDeleteCustomThemeStore.mockRejectedValueOnce(new Error("store down"));
await deleteCustomTheme(form({ id: "t1" }));
expect(mockRevalidatePath).not.toHaveBeenCalled();
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?deletedTheme=1");
expect(mockRedirect).toHaveBeenCalledWith("/admin/theme?error=1");
});
});
+6 -6
View File
@@ -104,7 +104,7 @@ export async function saveTheme(formData: FormData): Promise<void> {
});
revalidatePath("/", "layout");
} catch {
// ignore — page re-renders current state
return redirect("/admin/theme?error=1");
}
redirect("/admin/theme?saved=1");
}
@@ -128,7 +128,7 @@ export async function applyPreset(formData: FormData): Promise<void> {
});
revalidatePath("/", "layout");
} catch {
// ignore
return redirect("/admin/theme?error=1");
}
redirect(`/admin/theme?preset=${encodeURIComponent(name)}`);
}
@@ -149,7 +149,7 @@ export async function saveCustomTheme(formData: FormData): Promise<void> {
});
revalidatePath("/admin/theme");
} catch {
// ignore
return redirect("/admin/theme?error=1");
}
redirect("/admin/theme?savedTheme=1");
}
@@ -175,7 +175,7 @@ export async function applyCustomTheme(formData: FormData): Promise<void> {
});
revalidatePath("/", "layout");
} catch {
// ignore
return redirect("/admin/theme?error=1");
}
redirect(`/admin/theme?theme=${encodeURIComponent(theme.name)}`);
}
@@ -194,7 +194,7 @@ export async function renameCustomTheme(formData: FormData): Promise<void> {
await upsertCustomTheme(name, snapshot, id);
revalidatePath("/admin/theme");
} catch {
// ignore
return redirect("/admin/theme?error=1");
}
redirect("/admin/theme?renamed=1");
}
@@ -209,7 +209,7 @@ export async function deleteCustomTheme(formData: FormData): Promise<void> {
await deleteCustomThemeStore(id);
revalidatePath("/admin/theme");
} catch {
// ignore
return redirect("/admin/theme?error=1");
}
redirect("/admin/theme?deletedTheme=1");
}
+10 -5
View File
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { requirePermission } from "@/lib/admin/guard";
import { db, WebsiteWriteableBoxes } from "@/lib/db";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
import { logStaffActivity } from "@/lib/services/staff-activity";
@@ -72,8 +73,9 @@ export async function createBox(formData: FormData): Promise<void> {
targetType: "writeable_box",
targetId: Number(result.insertId),
});
} catch {
// DB unavailable — swallow and re-render.
} catch (err) {
// DB unavailable — keep the page usable, but record the failure.
logger.error("Failed to create writeable box", { err });
return;
}
@@ -116,7 +118,8 @@ export async function updateBox(formData: FormData): Promise<void> {
targetType: "writeable_box",
targetId: Number(id),
});
} catch {
} catch (err) {
logger.error("Failed to persist writeable box", { err });
return;
}
@@ -140,7 +143,8 @@ export async function deleteBox(formData: FormData): Promise<void> {
targetType: "writeable_box",
targetId: Number(id),
});
} catch {
} catch (err) {
logger.error("Failed to persist writeable box", { err });
return;
}
@@ -168,7 +172,8 @@ export async function toggleBox(formData: FormData): Promise<void> {
targetType: "writeable_box",
targetId: Number(id),
});
} catch {
} catch (err) {
logger.error("Failed to persist writeable box", { err });
return;
}
+1 -26
View File
@@ -4,6 +4,7 @@ import crypto from "node:crypto";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { isDynamicSuperAdmin } from "@/lib/admin/authorization-policy";
import { guardRank } from "@/lib/admin/rank-guard";
import { invalidateLoginCache } from "@/lib/auth";
import { hashPassword } from "@/lib/auth/password";
import { revokeUserCredentials } from "@/lib/auth/session-revocation";
@@ -329,32 +330,6 @@ export const removeBadge = adminAction(
},
);
// ── Rank guard helper ───────────────────────────────────────────────
async function guardRank(targetUserId: number, sessionRank: number) {
const [target] = await db
.select({
username: User.username,
rank: User.rank,
mail: User.mail,
})
.from(User)
.where(eq(User.id, targetUserId))
.limit(1);
if (!target) throw new ActionError("User not found");
// 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;
}
// ── Reset Password ──────────────────────────────────────────────────
const resetPasswordSchema = z.object({