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

+30 -8
View File
@@ -2,10 +2,11 @@ import "server-only";
import { asc, desc, eq, gte } from "drizzle-orm";
import { cached } from "@/lib/cache";
import { db, User, WebsiteTeams } from "@/lib/db";
import { CameraWeb, db, User, WebsiteTeams } from "@/lib/db";
import { logger } from "@/lib/logger";
import { apiCacheKey, redisCache } from "@/lib/redis-cache";
import { cacheNews } from "@/lib/services/news-cache";
import { cachedHomePayload } from "@/lib/services/home-payload";
import { getNewsList } from "@/lib/services/news-list";
import {
countArticles,
countOnline,
@@ -72,7 +73,7 @@ export async function warmPublicCaches(): Promise<void> {
}),
);
await warm("online_users", () =>
cached("online_users", ONLINE_TTL_MS, listOnlineUsers, {
cached("online_users", ONLINE_TTL_MS, () => listOnlineUsers(100), {
staleMs: 15_000,
}),
);
@@ -82,17 +83,38 @@ export async function warmPublicCaches(): Promise<void> {
await warm("api:teams", () =>
redisCache(apiCacheKey("teams"), 300, loadTeams, { staleMs: 600 }),
);
await warm("news:home", () =>
cacheNews(apiCacheKey("home"), 15_000, async () => ({ primed: true })),
// Prime the real payload the route serves — a placeholder here used to be
// cached under the shared key and served to every client after a restart.
await warm("news:home", cachedHomePayload);
await warm("news_list", () => getNewsList(4));
// The homepage reads its own roster/photo keys, so priming only the counters
// left the first visitor after a deploy paying for the sections anyway.
await warm("home_online_users", () =>
cached("home_online_users", 15_000, () => listOnlineUsers(12), {
staleMs: 30_000,
}),
);
await warm("home_recent_photos", () =>
cached("home_recent_photos", 60_000, loadRecentPhotos, {
staleMs: 120_000,
}),
);
}
async function listOnlineUsers() {
async function loadRecentPhotos() {
return db
.select({ username: User.username, look: User.look })
.select({ id: CameraWeb.id, url: CameraWeb.url })
.from(CameraWeb)
.orderBy(desc(CameraWeb.timestamp))
.limit(4);
}
async function listOnlineUsers(limit: number) {
return db
.select({ id: User.id, username: User.username, look: User.look })
.from(User)
.where(eq(User.online, "1"))
.limit(100);
.limit(limit);
}
async function loadStaff() {
+11 -1
View File
@@ -4,6 +4,7 @@ import path from "node:path";
import { promisify } from "node:util";
import { and, eq, type SQL, sql } from "drizzle-orm";
import { CatalogPages, db, execResult, ItemsBase, queryRows } from "@/lib/db";
import { isSafeAssetName } from "@/lib/furni/classname";
import { offerPurchasabilityProblems } from "@/lib/furni/offer-purchasability";
import { officialHabboEnrichmentWarning } from "@/lib/habbo-gamedata-hotel";
import { logger } from "@/lib/logger";
@@ -599,7 +600,6 @@ export async function importSingleFurni(params: {
}): Promise<ImportSingleResult> {
const {
id: originalId,
classname,
name,
description,
type,
@@ -615,6 +615,16 @@ export async function importSingleFurni(params: {
} = params;
const warnings: string[] = [];
// A classname becomes a file name below (swf/nitro/icon). It travels from a
// request body into `path.join`, so it must never be able to contain a path
// separator — otherwise a crafted value escapes the asset directories.
const classname = params.classname.trim();
if (!isSafeAssetName(classname)) {
throw new Error(
`Invalid furniture classname: ${JSON.stringify(params.classname)}`,
);
}
// Check if already exists by classname OR by spriteId (primary key collision).
const [existsByName] = await db
.select({
+51
View File
@@ -0,0 +1,51 @@
import "server-only";
import { and, count, desc, eq, or, sql } from "drizzle-orm";
import { db, User, WebsiteArticles } from "@/lib/db";
import { resolveHotelName } from "@/lib/hotel-name";
import { apiCacheKey, cacheSafe } from "@/lib/redis-cache";
import { cacheNews } from "@/lib/services/news-cache";
/**
* The `/api/home` landing payload: latest 4 published articles plus the current
* online player count. Shared as a loader so the cache warm-up can prime the
* exact same key the route reads — priming a placeholder instead made every
* instance serve a bogus `{ primed: true }` payload after each restart.
*/
export async function loadHomePayload() {
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,
});
}
/** Cached read of {@link loadHomePayload} under the route's own key. */
export async function cachedHomePayload() {
return cacheNews(apiCacheKey("home"), 15_000, loadHomePayload);
}
+62 -1
View File
@@ -1,5 +1,5 @@
import "server-only";
import { eq } from "drizzle-orm";
import { eq, inArray } from "drizzle-orm";
import { WebsiteProfilePrivacy } from "@/db/profile-privacy";
import { db } from "@/lib/db";
export const profilePrivacyKeys = [
@@ -40,3 +40,64 @@ export async function loadProfilePrivacy(userId: number) {
return { values: hiddenProfilePrivacy, unavailable: true };
}
}
function privacyFromRow(
row: Record<string, unknown> | undefined,
): ProfilePrivacy {
if (!row) return defaultProfilePrivacy;
return {
wallet:
row.wallet === undefined
? defaultProfilePrivacy.wallet
: Boolean(row.wallet),
online:
row.online === undefined
? defaultProfilePrivacy.online
: Boolean(row.online),
friends:
row.friends === undefined
? defaultProfilePrivacy.friends
: Boolean(row.friends),
photos:
row.photos === undefined
? defaultProfilePrivacy.photos
: Boolean(row.photos),
registered:
row.registered === undefined
? defaultProfilePrivacy.registered
: Boolean(row.registered),
};
}
/**
* Bulk variant for lists (leaderboard, search, rosters). One query for all ids
* and — exactly like the single-row loader — fails closed: a database error
* returns "hide everything" for every requested user rather than exposing
* wallet balances or online state of unknown visibility.
*/
export async function loadProfilePrivacyMap(
userIds: number[],
): Promise<Map<number, ProfilePrivacy>> {
const ids = [...new Set(userIds)].filter(
(id) => Number.isInteger(id) && id > 0,
);
if (ids.length === 0) return new Map();
try {
const rows = await db
.select()
.from(WebsiteProfilePrivacy)
.where(inArray(WebsiteProfilePrivacy.userId, ids));
const map = new Map<number, ProfilePrivacy>(
ids.map((id) => [id, defaultProfilePrivacy]),
);
for (const row of rows) {
map.set(
row.userId,
privacyFromRow(row as unknown as Record<string, unknown>),
);
}
return map;
} catch {
return new Map(ids.map((id) => [id, hiddenProfilePrivacy]));
}
}
+15
View File
@@ -1,6 +1,7 @@
import "server-only";
import { and, count, eq, or, sql } from "drizzle-orm";
import { cached } from "@/lib/cache";
import { CameraWeb, db, Rooms, User, WebsiteArticles } from "@/lib/db";
/**
@@ -73,3 +74,17 @@ export async function countOnline(): Promise<number> {
.where(eq(User.online, "1"));
return row?.total ?? 0;
}
// ── Shared hot read: online counter ───────────────────────────────────
//
// One function for every caller (homepage, login, register, headers, the client
// page and the warm-up). Each call site used to inline this, and the ones that
// omitted `staleMs` wrote an entry without a grace window, which made the key
// block on COUNT(*) at every TTL boundary.
export const ONLINE_COUNT_TTL_MS = 10_000;
export async function cachedOnlineCount(): Promise<number> {
return cached("online_count", ONLINE_COUNT_TTL_MS, countOnline, {
staleMs: 15_000,
});
}
+28
View File
@@ -0,0 +1,28 @@
/** Setting keys whose value must never be sent to the browser. */
const SECRET_SETTING_KEYS = new Set([
"turnstile_secret",
"recaptcha_secret",
"hcaptcha_secret",
"radio_azurecast_api_key",
"radio_sambroadcaster_password",
"radio_virtual_dj_password",
"radio_discord_webhook_url",
"gitea_token",
]);
/**
* A key is a secret when it is explicitly listed above, or when its name alone
* says so (`*_secret`, `*_password`, `*_api_key`, ...). Used by the settings UI
* to avoid shipping credentials in the RSC payload, and by the write actions to
* keep "blank means keep the stored value" semantics instead of wiping secrets.
*/
export function isSecretSettingKey(key: string): boolean {
const lower = key.toLowerCase();
if (SECRET_SETTING_KEYS.has(lower)) return true;
return /(^|_)(secret|password|passwd|token|api_?key|private_?key|credential)$/.test(
lower,
);
}
/** Replace a secret with a marker for UI rendering. */
export const SECRET_PLACEHOLDER = "••••••••";