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

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:
openhands committed 2026-10-09 16:19:48 +02:00
1 parent 3933214953
commit 6cc45d7413
150 files changed
+2137 -759

No files matched your search

+14 -3
View File
@@ -5,7 +5,7 @@ import { invalidateCatalogTotals } from "@/features/catalog/server/catalog-total
import { apiError, apiOk } from "@/lib/api";
import { withAdmin } from "@/lib/api-handler";
import { db, ItemsBase, queryRows } from "@/lib/db";
import { normalizeClassname } from "@/lib/furni/classname";
import { isSafeAssetName, normalizeClassname } from "@/lib/furni/classname";
import { localFurnitureStatus } from "@/lib/furni/local-presence";
import { PERMS } from "@/lib/permissions";
import { logAudit } from "@/lib/services/audit";
@@ -709,9 +709,20 @@ export const PATCH = withAdmin(
[];
for (const item of items) {
const starIdx = item.classname.indexOf("*");
const normalised = item.classname.trim();
// The classname is joined straight into a `.nitro` file path, so a
// separator/looking payload must never get that far.
if (!isSafeAssetName(normalised)) {
results.push({
classname: item.classname,
ok: false,
warning: "Invalid classname",
});
continue;
}
const starIdx = normalised.indexOf("*");
const baseClassname =
starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname;
starIdx !== -1 ? normalised.substring(0, starIdx) : normalised;
const nitroPath = path.join(
/*turbopackIgnore: true*/ nitroDir,
`${baseClassname}.nitro`,
+40 -4
View File
@@ -6,11 +6,20 @@ import { PERMS } from "@/lib/permissions";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
/** Currency grants are capped: an unbounded `amount` minted an economy-breaking
* balance with a single request. */
function positiveAmount(amount: number): boolean {
return Number.isInteger(amount) && amount > 0 && amount <= MAX_CURRENCY_GRANT;
}
const MAX_CURRENCY_GRANT = 1_000_000;
export const POST = withAdmin(
{ permission: PERMS.USERS_EDIT },
async (request, context) => {
const staffId = context.session.user.id;
const staffRank = context.session.user.rank;
const isSuper = context.permissions.isSuperAdmin;
const formData = await request.formData();
const userId = Number(formData.get("userId"));
const username = String(formData.get("username") || "");
@@ -23,6 +32,33 @@ export const POST = withAdmin(
);
}
// Every branch below acts on a live account, so the rank guard that the
// set_rank branch already applies belongs to all of them: staff may not
// act on users at or above their own rank unless they are the hotel's
// dynamic owner.
if (action !== "set_rank") {
const [target] = await db
.select({ rank: User.rank })
.from(User)
.where(eq(User.id, userId))
.limit(1);
if (!target) {
return NextResponse.json(
{ success: false, message: "User not found" },
{ status: 404 },
);
}
if (!isSuper && target.rank >= staffRank) {
return NextResponse.json(
{
success: false,
message: "Cannot act on a user at or above your rank",
},
{ status: 403 },
);
}
}
if (action === "set_rank") {
const rank = Number(formData.get("rank") || "0");
if (!Number.isInteger(rank) || rank < 1) {
@@ -141,7 +177,7 @@ export const POST = withAdmin(
if (action === "give_credits") {
const credits = Number(formData.get("credits") || "0");
if (!credits || credits <= 0) {
if (!positiveAmount(credits)) {
return NextResponse.json(
{ success: false, message: "Invalid credit amount" },
{ status: 400 },
@@ -166,7 +202,7 @@ export const POST = withAdmin(
if (action === "give_duckets") {
const amount = Number(formData.get("amount") || "0");
if (!amount || amount <= 0) {
if (!positiveAmount(amount)) {
return NextResponse.json(
{ success: false, message: "Invalid duckets amount" },
{ status: 400 },
@@ -188,7 +224,7 @@ export const POST = withAdmin(
if (action === "give_diamonds") {
const amount = Number(formData.get("amount") || "0");
if (!amount || amount <= 0) {
if (!positiveAmount(amount)) {
return NextResponse.json(
{ success: false, message: "Invalid diamonds amount" },
{ status: 400 },
@@ -213,7 +249,7 @@ export const POST = withAdmin(
if (action === "give_points") {
const amount = Number(formData.get("amount") || "0");
if (!amount || amount <= 0) {
if (!positiveAmount(amount)) {
return NextResponse.json(
{ success: false, message: "Invalid points amount" },
{ status: 400 },
+6
View File
@@ -23,6 +23,12 @@ export async function POST(request: Request) {
!request.headers.get("content-type")?.startsWith("application/json")
)
return new Response(null, { status: 403 });
// The IP bucket is rotatable, so also require the browser's own fetch
// metadata: a script hammering this endpoint from another site is
// `cross-site`, while a real in-page reporter is never.
const fetchSite = request.headers.get("sec-fetch-site");
if (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none")
return new Response(null, { status: 403 });
const limit = await rateLimit(`cms-error:${await clientIp()}`, 20, 60000);
if (!limit.ok) return new Response(null, { status: 429 });
const reader = request.body?.getReader();
+2 -38
View File
@@ -1,11 +1,7 @@
import { and, count, desc, eq, or, sql } from "drizzle-orm";
import { env } from "@/env";
import { apiJson } from "@/lib/api";
import { db, User, WebsiteArticles } from "@/lib/db";
import { resolveHotelName } from "@/lib/hotel-name";
import { logger } from "@/lib/logger";
import { apiCacheKey, cacheSafe } from "@/lib/redis-cache";
import { cacheNews } from "@/lib/services/news-cache";
import { cachedHomePayload } from "@/lib/services/home-payload";
/**
* GET /api/home — combined landing payload: the latest 4 website_articles and
@@ -14,39 +10,7 @@ import { cacheNews } from "@/lib/services/news-cache";
*/
export async function GET(_req: Request) {
try {
const data = await cacheNews(apiCacheKey("home"), 15_000, async () => {
const [articles, onlineRows, hotelName] = await Promise.all([
db
.select({
id: WebsiteArticles.id,
title: WebsiteArticles.title,
slug: WebsiteArticles.slug,
shortStory: WebsiteArticles.shortStory,
image: WebsiteArticles.image,
createdAt: WebsiteArticles.createdAt,
})
.from(WebsiteArticles)
.where(
and(
eq(WebsiteArticles.status, "published"),
or(
sql`${WebsiteArticles.publishAt} IS NULL`,
sql`${WebsiteArticles.publishAt} <= NOW()`,
),
),
)
.orderBy(desc(WebsiteArticles.createdAt))
.limit(4),
db.select({ total: count() }).from(User).where(eq(User.online, "1")),
resolveHotelName(),
]);
return cacheSafe({
articles,
online: onlineRows[0]?.total ?? 0,
hotelName,
});
});
return apiJson(data);
return apiJson(await cachedHomePayload());
} catch (error) {
logger.error("Public news query failed", { module: "news", error });
return apiJson(
+34 -6
View File
@@ -14,11 +14,29 @@ const CURRENCY_TYPE: Record<Exclude<LeaderboardType, "credits">, number> = {
duckets: 0,
};
type Row = { rank: number; username: string; look: string; value: number };
type Row = {
rank: number;
userId: number;
username: string;
look: string;
value: number;
};
/** Hidden-wallet users must not be listed, exactly like on the page. */
async function withoutHiddenWallets<T extends { userId: number }>(
rows: T[],
): Promise<T[]> {
const { loadProfilePrivacyMap } = await import(
"@/lib/services/profile-privacy"
);
const privacy = await loadProfilePrivacyMap(rows.map((r) => r.userId));
return rows.filter((r) => privacy.get(r.userId)?.wallet !== false);
}
async function loadCreditsRows(): Promise<Row[]> {
const users = await db
.select({
userId: User.id,
username: User.username,
look: User.look,
credits: User.credits,
@@ -26,8 +44,9 @@ async function loadCreditsRows(): Promise<Row[]> {
.from(User)
.orderBy(desc(User.credits))
.limit(20);
return users.map((u, i) => ({
return (await withoutHiddenWallets(users)).map((u, i) => ({
rank: i + 1,
userId: u.userId,
username: u.username,
look: u.look,
value: u.credits,
@@ -55,15 +74,24 @@ async function loadCurrencyRows(type: number): Promise<Row[]> {
top.map((t) => t.userId),
),
);
const byId = new Map(users.map((u) => [u.id, u]));
const allowed = await withoutHiddenWallets(top);
const allowedIds = new Set(allowed.map((t) => t.userId));
const byId = new Map(
users.filter((u) => allowedIds.has(u.id)).map((u) => [u.id, u]),
);
return top
return allowed
.map((t) => {
const u = byId.get(t.userId);
if (!u) return null;
return { username: u.username, look: u.look, value: t.amount };
return {
userId: u.id,
username: u.username,
look: u.look,
value: t.amount,
};
})
.filter((r): r is Omit<Row, "rank"> => r !== null)
.filter((r) => r !== null)
.map((r, i) => ({ rank: i + 1, ...r }));
}
+12 -5
View File
@@ -1,13 +1,20 @@
import { existsSync, readdirSync, statSync } from "node:fs";
import { resolve } from "node:path";
import { NextResponse } from "next/server";
import { apiOk } from "@/lib/api";
import { withAdmin } from "@/lib/api-handler";
import { MEDIA_ROOT } from "@/lib/media-storage";
import { PERMS } from "@/lib/permissions";
export async function GET() {
/**
* Directory listing for the admin media picker. It used to be world-readable and
* unrated, which handed every visitor a complete inventory of uploaded media
* (logo/favicon paths included) plus their timestamps.
*/
export const GET = withAdmin({ permission: PERMS.PAGES_EDIT }, async () => {
const dir = MEDIA_ROOT;
// eslint-disable-next-line security/detect-non-literal-fs-filename
if (!existsSync(dir)) {
return NextResponse.json({ files: [] });
return apiOk({ files: [] });
}
// eslint-disable-next-line security/detect-non-literal-fs-filename
const files = readdirSync(dir)
@@ -23,5 +30,5 @@ export async function GET() {
})
.sort((a, b) => b.uploaded - a.uploaded);
return NextResponse.json({ files });
}
return apiOk({ files });
});
+13 -1
View File
@@ -31,8 +31,20 @@ export async function GET(req: Request) {
.limit(take)
.offset(skip),
]);
// Photo privacy is a per-user setting, so the API honours it like
// the /photos page does.
const { loadProfilePrivacyMap } = await import(
"@/lib/services/profile-privacy"
);
const photoPrivacy = await loadProfilePrivacyMap(
photos.map((p) => p.userId),
);
return cacheSafe({
data: photos,
data: photos.filter(
(p) => photoPrivacy.get(p.userId)?.photos !== false,
),
meta: {
page,
perPage,
+9
View File
@@ -4,6 +4,7 @@ import { bearerUserId } from "@/lib/api-auth";
import { db, RadioShouts, User } from "@/lib/db";
import { rateLimit } from "@/lib/rate-limit";
import { apiCacheKey, redisCache } from "@/lib/redis-cache";
import { moderateOrThrow } from "@/lib/services/moderation";
// Latest 50 radio shouts with their author's username/look resolved. Mirrors the
// query behind the public /radio/shouts page (radio_shouts ordered by created_at
@@ -93,6 +94,14 @@ export async function POST(req: Request) {
);
}
// The same word filter the server action applies — the API path used to
// skip it entirely, so a filtered message could be posted with one fetch.
try {
await moderateOrThrow(message);
} catch (error) {
return apiError((error as Error).message, 422);
}
try {
const now = new Date();
await db.insert(RadioShouts).values({
+11 -2
View File
@@ -23,6 +23,7 @@ export async function GET(
async () => {
const [row] = await db
.select({
id: User.id,
username: User.username,
look: User.look,
motto: User.motto,
@@ -39,13 +40,21 @@ export async function GET(
return null;
}
// Wallet / online visibility are per-user settings; the public API
// used to hand both out unconditionally, which made bulk scraping
// of hidden wallets possible.
const { loadProfilePrivacy } = await import(
"@/lib/services/profile-privacy"
);
const privacy = await loadProfilePrivacy(row.id);
return cacheSafe({
username: row.username,
look: row.look,
motto: row.motto,
rank: row.rank,
credits: row.credits,
online: row.online === "1",
credits: privacy.values.wallet ? row.credits : null,
online: privacy.values.online ? row.online === "1" : null,
accountCreated: row.accountCreated,
});
},