P1-P3 admin cleanup: rank guard, SSRF guard, count caching, dead code removal, pagination rewrite
CI / check (push) Canceled after 0s
CI / tests-unit (push) Canceled after 0s
CI / tests-integration (push) Canceled after 0s
CI / tests-ui (push) Canceled after 0s
CI / preflight (push) Canceled after 0s
CI / deploy (push) Canceled after 0s
Gitea Runner Clean Test / test-job (push) Canceled after 0s
Gitea Actions Runner Test / test-job (push) Canceled after 0s

- 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", {
+57 -10
View File
@@ -8,12 +8,16 @@ const state = vi.hoisted(() => ({
fail: false,
giveBadge: vi.fn(async () => undefined),
requirePermission: vi.fn(),
tryGuardRank: vi.fn(),
revalidatePath: vi.fn(),
}));
vi.mock("@/lib/admin/guard", () => ({
requirePermission: state.requirePermission,
}));
vi.mock("@/lib/admin/rank-guard", () => ({
tryGuardRank: state.tryGuardRank,
}));
vi.mock("@/lib/permissions", () => ({
PERMS: { CATALOG_EDIT: "admin.catalog.edit" },
}));
@@ -55,6 +59,10 @@ beforeEach(() => {
state.insertValues.mockResolvedValue([{}]);
state.giveBadge.mockResolvedValue(undefined);
state.requirePermission.mockResolvedValue({ id: 1, rank: 7, username: "a" });
state.tryGuardRank.mockResolvedValue({
ok: true,
target: { username: "u", rank: 1, mail: null },
});
});
describe("giveBadge", () => {
@@ -64,6 +72,7 @@ describe("giveBadge", () => {
await giveBadge(form("3", "ACH_Test"));
expect(state.requirePermission).toHaveBeenCalledWith(PERMS.CATALOG_EDIT);
expect(state.tryGuardRank).toHaveBeenCalledWith(3, 7);
expect(state.giveBadge).toHaveBeenCalledWith(3, "ACH_Test");
expect(state.insertValues).toHaveBeenCalledWith({
userId: 3,
@@ -97,19 +106,42 @@ describe("giveBadge", () => {
});
});
it("does not persist a duplicate badge", async () => {
it("does not persist a duplicate badge and skips revalidation", async () => {
state.existingRows = [{ id: 10 }];
await giveBadge(form("4", "DUP"));
expect(state.giveBadge).toHaveBeenCalledWith(4, "DUP");
expect(state.insertValues).not.toHaveBeenCalled();
expect(state.revalidatePath).toHaveBeenCalledWith("/admin/badges");
expect(state.revalidatePath).not.toHaveBeenCalled();
});
it("skips a user at or above the actor rank", async () => {
state.tryGuardRank.mockResolvedValueOnce({ ok: false, reason: "rank" });
await giveBadge(form("4", "DUP"));
expect(state.giveBadge).not.toHaveBeenCalled();
expect(state.insertValues).not.toHaveBeenCalled();
expect(state.revalidatePath).not.toHaveBeenCalled();
});
it("skips an unknown user", async () => {
state.tryGuardRank.mockResolvedValueOnce({
ok: false,
reason: "not_found",
});
await giveBadge(form("404", "DUP"));
expect(state.giveBadge).not.toHaveBeenCalled();
expect(state.insertValues).not.toHaveBeenCalled();
});
it("returns early for a non-positive user id", async () => {
await giveBadge(form("0", "X"));
expect(state.tryGuardRank).not.toHaveBeenCalled();
expect(state.giveBadge).not.toHaveBeenCalled();
expect(state.insertValues).not.toHaveBeenCalled();
expect(state.revalidatePath).not.toHaveBeenCalled();
@@ -138,21 +170,36 @@ describe("giveBadge", () => {
expect(state.giveBadge).toHaveBeenCalledWith(5, "a".repeat(32));
});
it("swallows persistence failures after the rcon grant", async () => {
state.insertValues.mockRejectedValueOnce(new Error("db down"));
it("caps bulk user and code lists", async () => {
const users = Array.from({ length: 250 }, (_, i) => i + 1).join(",");
const codes = Array.from({ length: 250 }, (_, i) => `C${i}`).join(",");
await expect(giveBadge(form("6", "BEST"))).resolves.toBeUndefined();
await giveBadge(form(users, codes));
expect(state.giveBadge).toHaveBeenCalledWith(6, "BEST");
expect(state.revalidatePath).toHaveBeenCalledWith("/admin/badges");
// 100 users x 100 codes = 10k pairs, capped to MAX_PAIRS (500).
const calls = state.insertValues.mock.calls.length;
expect(calls).toBeLessThanOrEqual(500);
});
it("swallows select failures and still revalidates", async () => {
it("throws when persistence fails instead of swallowing it", async () => {
state.insertValues.mockRejectedValueOnce(new Error("db down"));
await expect(giveBadge(form("6", "BEST"))).rejects.toThrow(
"Failed to persist",
);
expect(state.giveBadge).toHaveBeenCalledWith(6, "BEST");
expect(state.revalidatePath).not.toHaveBeenCalled();
});
it("throws when the select fails instead of reporting a false success", async () => {
state.fail = true;
await expect(giveBadge(form("6", "BEST"))).resolves.toBeUndefined();
await expect(giveBadge(form("6", "BEST"))).rejects.toThrow(
"Failed to persist",
);
expect(state.revalidatePath).toHaveBeenCalledWith("/admin/badges");
expect(state.revalidatePath).not.toHaveBeenCalled();
});
it("propagates a permission denial", async () => {
+36 -15
View File
@@ -3,12 +3,18 @@
import { and, eq, max } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { requirePermission } from "@/lib/admin/guard";
import { tryGuardRank } from "@/lib/admin/rank-guard";
import { db, UsersBadges } from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import { rcon } from "@/lib/services/rcon";
// Bound the bulk surface so a paste bomb cannot turn into an unbounded N+1.
const MAX_USERS = 100;
const MAX_CODES = 100;
const MAX_PAIRS = 500;
export async function giveBadge(formData: FormData): Promise<void> {
await requirePermission(PERMS.CATALOG_EDIT);
const staff = await requirePermission(PERMS.CATALOG_EDIT);
// Support comma-separated userIds and/or codes for bulk operations
const userIdInput = String(formData.get("userId") ?? "").trim();
@@ -18,30 +24,40 @@ export async function giveBadge(formData: FormData): Promise<void> {
.split(",")
.map((s) => s.trim())
.filter(Boolean)
.slice(0, MAX_USERS)
: [];
const codes = codeInput
? codeInput
.split(",")
.map((s) => s.trim())
.filter(Boolean)
.slice(0, MAX_CODES)
: [];
if (userIds.length === 0 || codes.length === 0) {
return;
}
// Process each user/code combination
let granted = false;
for (const userId of userIds) {
for (const code of codes) {
if (!(Number(userId) > 0) || code.length === 0) continue;
let granted = 0;
let failures = 0;
for (const rawUserId of userIds) {
const userId = Number(rawUserId);
if (!(userId > 0)) continue;
// Never hand badges to a target at or above the actor's rank.
const guard = await tryGuardRank(userId, staff.rank);
if (!guard.ok) continue;
for (const rawCode of codes) {
if (granted + failures >= MAX_PAIRS) break;
// Truncate badge code to 32 characters.
const truncatedCode = code.slice(0, 32);
const truncatedCode = rawCode.slice(0, 32);
if (truncatedCode.length === 0) continue;
// Fire the emulator command so the badge appears live for online users.
// Offline/unreachable emulator must not block the DB persistence.
try {
await rcon.giveBadge(Number(userId), truncatedCode);
await rcon.giveBadge(userId, truncatedCode);
} catch {
// ignore rcon errors per pair
}
@@ -55,7 +71,7 @@ export async function giveBadge(formData: FormData): Promise<void> {
.from(UsersBadges)
.where(
and(
eq(UsersBadges.userId, Number(userId)),
eq(UsersBadges.userId, userId),
eq(UsersBadges.badgeCode, truncatedCode),
),
)
@@ -64,23 +80,28 @@ export async function giveBadge(formData: FormData): Promise<void> {
const [agg] = await db
.select({ maxSlot: max(UsersBadges.slotId) })
.from(UsersBadges)
.where(eq(UsersBadges.userId, Number(userId)));
.where(eq(UsersBadges.userId, userId));
const slotId = (agg?.maxSlot ?? 0) + 1;
await db.insert(UsersBadges).values({
userId: Number(userId),
userId,
slotId,
badgeCode: truncatedCode,
});
granted++;
}
} catch {
// Best-effort: the RCON grant already succeeded for online users.
// A persistence failure must be visible, not silently dropped.
failures++;
}
granted = true;
}
}
if (granted) {
if (failures > 0) {
throw new Error(
`Failed to persist ${failures} badge grant(s); the emulator may have succeeded for some users`,
);
}
if (granted > 0) {
revalidatePath("/admin/badges");
}
}
+71 -7
View File
@@ -22,7 +22,7 @@ vi.mock("@/lib/auth", () => ({
signOut: vi.fn(),
}));
import { Ban, db, User } from "@/lib/db";
import { Ban, db } from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import { createBan, liftBan } from "./admin-bans";
@@ -42,6 +42,20 @@ vi.mock("@/lib/admin/guard", () => ({
requirePermissionRateLimited: mockRequirePermissionRateLimited,
}));
const mockTryGuardRank = vi.hoisted(() => vi.fn());
vi.mock("@/lib/admin/rank-guard", () => ({
tryGuardRank: mockTryGuardRank,
}));
const mockRedirect = vi.hoisted(() =>
vi.fn(() => {
throw new Error("NEXT_REDIRECT");
}),
);
vi.mock("next/navigation", () => ({
redirect: mockRedirect,
}));
// Hoisted mocks for internal db functions
const hoistedInsertValues = vi.hoisted(() => vi.fn());
const hoistedDeleteWhere = vi.hoisted(() => vi.fn());
@@ -61,7 +75,6 @@ vi.mock("@/lib/db", () => {
select: vi.fn(() => ({ from: hoistedSelectFrom })),
},
Ban: { id: "Ban.id", userId: "Ban.userId" },
User: { id: "User.id", username: "User.username" },
};
});
@@ -93,7 +106,11 @@ beforeEach(() => {
mockRequirePermissionRateLimited.mockResolvedValue({ id: 100, rank: 7 });
hoistedInsertValues.mockResolvedValue([{ insertId: 1 }]);
hoistedDeleteWhere.mockResolvedValue([{ affectedRows: 1 }]);
hoistedSelectLimit.mockResolvedValue([{ username: "testuser" }]);
hoistedSelectLimit.mockResolvedValue([{ userId: 5 }]);
mockTryGuardRank.mockResolvedValue({
ok: true,
target: { username: "testuser", rank: 1, mail: null },
});
mockHeaders.mockReturnValue(new Map());
});
@@ -110,6 +127,7 @@ describe("createBan", () => {
expect(mockRequirePermissionRateLimited).toHaveBeenCalledWith(
PERMS.USERS_BAN,
);
expect(mockTryGuardRank).toHaveBeenCalledWith(1, 7);
expect(db.insert).toHaveBeenCalledWith(Ban);
expect(hoistedInsertValues).toHaveBeenCalledWith(
expect.objectContaining({
@@ -156,6 +174,7 @@ describe("createBan", () => {
await createBan(formData);
expect(mockTryGuardRank).not.toHaveBeenCalled();
expect(db.insert).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
});
@@ -169,27 +188,45 @@ describe("createBan", () => {
await createBan(formData);
expect(mockTryGuardRank).not.toHaveBeenCalled();
expect(db.insert).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
});
it("disconnects user via RCON if user found", async () => {
it("disconnects user via RCON using the guarded username", async () => {
mockTryGuardRank.mockResolvedValueOnce({
ok: true,
target: { username: "anotheruser", rank: 1, mail: null },
});
const formData = new FormData();
formData.append("userId", "3");
formData.append("type", "account");
formData.append("reason", "Test reason");
hoistedSelectLimit.mockResolvedValueOnce([{ username: "anotheruser" }]);
await createBan(formData);
expect(mockTryGuardRank).toHaveBeenCalledWith(3, 7);
expect(mockRconDisconnectUser).toHaveBeenCalledWith(3, "anotheruser");
expect(mockEq).toHaveBeenCalledWith(User.id, 3);
});
it("refuses to ban a user with equal or higher rank", async () => {
mockTryGuardRank.mockResolvedValueOnce({ ok: false, reason: "rank" });
const formData = new FormData();
formData.append("userId", "3");
formData.append("type", "account");
formData.append("reason", "Test reason");
await expect(createBan(formData)).rejects.toThrow("NEXT_REDIRECT");
expect(mockRedirect).toHaveBeenCalledWith("/admin/bans?error=rank");
expect(db.insert).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
});
});
describe("liftBan", () => {
it("lifts an existing ban and logs activity", async () => {
hoistedSelectLimit.mockResolvedValueOnce([{ userId: 5 }]);
const formData = new FormData();
formData.append("id", "123");
@@ -198,6 +235,8 @@ describe("liftBan", () => {
expect(mockRequirePermissionRateLimited).toHaveBeenCalledWith(
PERMS.USERS_BAN,
);
expect(mockEq).toHaveBeenCalledWith(Ban.id, 123);
expect(mockTryGuardRank).toHaveBeenCalledWith(5, 7);
expect(db.delete).toHaveBeenCalledWith(Ban);
expect(hoistedDeleteWhere).toHaveBeenCalledWith(mockEq(Ban.id, 123));
expect(mockLogStaffActivity).toHaveBeenCalledWith(
@@ -209,12 +248,37 @@ describe("liftBan", () => {
expect(mockRevalidatePath).toHaveBeenCalledWith("/admin/bans");
});
it("refuses to lift a ban placed on an equal or higher rank user", async () => {
hoistedSelectLimit.mockResolvedValueOnce([{ userId: 5 }]);
mockTryGuardRank.mockResolvedValueOnce({ ok: false, reason: "rank" });
const formData = new FormData();
formData.append("id", "123");
await expect(liftBan(formData)).rejects.toThrow("NEXT_REDIRECT");
expect(mockRedirect).toHaveBeenCalledWith("/admin/bans?error=rank");
expect(hoistedDeleteWhere).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
});
it("tolerates a lift when the targeted user no longer exists", async () => {
hoistedSelectLimit.mockResolvedValueOnce([{ userId: 5 }]);
mockTryGuardRank.mockResolvedValueOnce({ ok: false, reason: "not_found" });
const formData = new FormData();
formData.append("id", "123");
await liftBan(formData);
expect(db.delete).toHaveBeenCalledWith(Ban);
});
it("does not delete if ban id is not positive", async () => {
const formData = new FormData();
formData.append("id", "0");
await liftBan(formData);
expect(mockEq).not.toHaveBeenCalled();
expect(db.delete).not.toHaveBeenCalled();
expect(hoistedDeleteWhere).not.toHaveBeenCalled();
expect(mockLogStaffActivity).not.toHaveBeenCalled();
+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({