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
+30
-34
@@ -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<void> {
|
||||
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}`;
|
||||
}
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
.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 })
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
+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 } };
|
||||
}
|
||||
@@ -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<string, unknown>,
|
||||
): void {
|
||||
try {
|
||||
logAudit({ userId, action, target: "User", targetId, after });
|
||||
} catch {
|
||||
/* auditing must never fail the command it describes */
|
||||
}
|
||||
}
|
||||
|
||||
async function requireRconOk(ok: boolean): Promise<void> {
|
||||
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();
|
||||
},
|
||||
|
||||
@@ -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(() =>
|
||||
|
||||
@@ -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<void> {
|
||||
.limit(1);
|
||||
if (!recipient) {
|
||||
outcome = "invalid";
|
||||
} else if (!(await isAllowed(message)).ok) {
|
||||
outcome = "invalid";
|
||||
} else {
|
||||
await db.insert(MessengerOffline).values({
|
||||
userId: friendId,
|
||||
|
||||
@@ -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", "[email protected]");
|
||||
|
||||
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
||||
|
||||
expect(selectLimit).toHaveBeenCalled();
|
||||
expect(selectWhere).toHaveBeenCalled();
|
||||
expect(insertOnDup).toHaveBeenCalled();
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
"[email protected]",
|
||||
@@ -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", "[email protected]");
|
||||
|
||||
@@ -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<void> {
|
||||
const email = String(formData.get("email") ?? "")
|
||||
.normalize("NFC")
|
||||
@@ -40,12 +54,23 @@ export async function requestReset(formData: FormData): Promise<void> {
|
||||
// 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<void> {
|
||||
|
||||
// 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<void> {
|
||||
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<void> {
|
||||
}
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
+63
-20
@@ -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<string, unknown>,
|
||||
allowed: readonly string[],
|
||||
): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
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<string, unknown>) {
|
||||
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<typeof Items.$inferInsert>)
|
||||
.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<string, unknown>) {
|
||||
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<typeof Rooms.$inferInsert>)
|
||||
.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}`);
|
||||
}
|
||||
@@ -14,8 +14,13 @@ const state = vi.hoisted(() => ({
|
||||
selectQueue: [] as Queue,
|
||||
rows: [] as Array<Record<string, unknown>>,
|
||||
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<unknown>, 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<unknown>, 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",
|
||||
|
||||
@@ -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<void> {
|
||||
.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<void> {
|
||||
.slice(0, MESSAGE_MAX);
|
||||
if (!message) {
|
||||
outcome = "invalid";
|
||||
} else if (!(await isAllowed(message)).ok) {
|
||||
outcome = "invalid";
|
||||
} else {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
|
||||
@@ -78,6 +78,22 @@ async function verifyTwoFactorCode(
|
||||
export async function beginTwoFactor(): Promise<void> {
|
||||
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<void> {
|
||||
.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");
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<void> {
|
||||
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)
|
||||
|
||||
@@ -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(),
|
||||
}));
|
||||
|
||||
+36
-5
@@ -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();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user