feat: harden atoms-nexst against review findings (37 items)
Gitea Actions Runner Test / test-job (push) Successful in 2s
CI / check (push) Successful in 30s
CI / tests-integration (push) Successful in 1m42s
CI / tests-unit (push) Failing after 1m49s
CI / tests-ui (push) Successful in 2m31s
CI / preflight (push) Skipped
CI / deploy (push) Skipped
Gitea Actions Runner Test / test-job (push) Successful in 2s
CI / check (push) Successful in 30s
CI / tests-integration (push) Successful in 1m42s
CI / tests-unit (push) Failing after 1m49s
CI / tests-ui (push) Successful in 2m31s
CI / preflight (push) Skipped
CI / deploy (push) Skipped
Second review pass covering security, performance, admin tooling and the public/room flows. All HIGH and MEDIUM findings from the audit are resolved; nothing in this commit changes the visible feature set. Authentication & session security - CSP is now set on the request headers in the proxy, which is what Next.js uses to derive the render nonce, so the nonce is effective. - 2FA: an already-enabled user cannot re-enroll, the setup endpoint is rate-limited per account, and confirmed codes are persisted so the second secret no longer silently never applies. - Password reset revokes the ticket, authTicket and all personal access tokens, and bumps the token version so existing sessions die. The same revocation is now wired into the staff-side password reset. - /reset and /verify return a stable error code instead of raw text; the mail lookups are ordered by id so duplicates cannot vary between runs. - Resending the verification mail gets a per-address cooldown on top of the per-user limit. - Issue API tokens with the narrower radio/ticket ability set instead of "*". Authorization & input handling - Mid-rank staff can no longer keep dynamically granted non-view admin.* permissions: existing grants are revoked by migration and the grant lookup is restricted to "%.view". Rank guards use the dynamic super-admin check. - Alerting a user is permission-checked and audited like the other tools. - Material mutations (giveCredits/giveDuckets/giveDiamonds, the admin user actions route, bulk user actions) are capped and rank-guarded, and bulk ids are bounded. - updateRoom / updateRoomItem write through a field allowlist, and items may only be edited through their own room. - Classnames reaching the filesystem are validated before use so a crafted value cannot escape the asset directories. - The word filter now also covers offline mails, guild forum threads and replies, and user mottos. - Media uploads are validated by magic bytes, /api/media requires the page edit permission, APP_URL must be configured once mail is enabled, and the diagnostics error route checks the fetch site header. Admin tooling - Secret settings render masked and cannot be overwritten with a blank or an arbitrary raw key; radio credentials are new password inputs. - Commandocentrum balance changes are audited. - Admin list pagination reads the caller's per-page instead of the max, and the log exporter caps offset and search length. Performance - Catalog translations are cached per module, with a cheap revision hash; the public online count uses a stale window instead of hammering the DB. - The cache warmup now primes the payload the home route actually reads. - TopHeader batches its queries into one round trip, and LCP avatars load eagerly. - motion/react and sonner are no longer part of the root layout; the nav dropdown and mobile nav panels are lazy client chunks. Anonymous visitors again get the navigation chrome, and public pages get an edge cacheable response. Accessibility - Nested <main> elements in phase pages became <section>; the page entrance and route progress animations are pure CSS that respect reduced motion.
This commit is contained in:
1 parent
3933214953
commit
6cc45d7413
150 files changed
+2137
-759
No files matched your search
+101
-32
@@ -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<void> {
|
||||
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<ActionResult<{ unbanned: number; total: number }>> {
|
||||
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<ActionResult<{ banned: number }>> {
|
||||
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<ActionResult<{ userId: number; untilUnix: number }>> {
|
||||
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 } };
|
||||
}
|
||||
Reference in new issue
Block a user