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
@@ -50,8 +50,10 @@ export async function fetchAdminList<TRow>(
|
||||
const rawParams = await searchParamsPromise;
|
||||
const sp = new URLSearchParams(rawParams);
|
||||
const parsed = parseListParams(sp);
|
||||
// `parsed.perPage` is already clamped to 1..100; re-reading the raw value
|
||||
// here let `?perPage=100000` pass straight into LIMIT.
|
||||
const perPage = config.defaultPerPage
|
||||
? Number(rawParams.perPage) || config.defaultPerPage
|
||||
? parsed.perPage || config.defaultPerPage
|
||||
: parsed.perPage;
|
||||
|
||||
const { rows, total } = await config.fetch({
|
||||
|
||||
+16
-2
@@ -74,7 +74,21 @@ export async function bearerUserId(
|
||||
}
|
||||
}
|
||||
|
||||
/** Mint a new token for a user. Returns the plaintext (shown once). */
|
||||
/**
|
||||
* Mint a new token for a user. Returns the plaintext (shown once).
|
||||
*
|
||||
* New tokens get the narrow read/write set every client actually needs. The old
|
||||
* `abilities: ["*"]` meant a leaked token could call *any* endpoint, including
|
||||
* destructive ones; the wildcard is kept working for reading old rows so
|
||||
* existing integrations do not break.
|
||||
*/
|
||||
const DEFAULT_TOKEN_ABILITIES: PersonalTokenAbility[] = [
|
||||
"radio:read",
|
||||
"radio:write",
|
||||
"tickets:read",
|
||||
"tickets:write",
|
||||
];
|
||||
|
||||
export async function issueToken(
|
||||
userId: number,
|
||||
name = "api",
|
||||
@@ -86,7 +100,7 @@ export async function issueToken(
|
||||
...personalTokenScope(userId),
|
||||
name: name.slice(0, 100),
|
||||
token: hashToken(plaintext),
|
||||
abilities: '["*"]',
|
||||
abilities: JSON.stringify(DEFAULT_TOKEN_ABILITIES),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { invalidateJwtVersionCache } from "@/lib/auth/jwt-version-cache";
|
||||
import { personalTokenScope } from "@/lib/auth/personal-token-scope";
|
||||
import { db, PersonalAccessTokens, User } from "@/lib/db";
|
||||
import { logger } from "@/lib/logger";
|
||||
|
||||
/**
|
||||
* Kill every live credential for a user: CMS JWTs (by bumping
|
||||
* `website_jwt_version`, which the `jwt` callback re-checks), the game SSO
|
||||
* ticket, and the API bearer tokens.
|
||||
*
|
||||
* Needed by sign-out-everywhere *and* by every password change: without it,
|
||||
* resetting a compromised password leaves the attacker's stolen session
|
||||
* cookie and API token working until they expire on their own.
|
||||
*/
|
||||
export async function revokeUserCredentials(userId: number): Promise<void> {
|
||||
try {
|
||||
await db
|
||||
.update(User)
|
||||
.set({
|
||||
websiteJwtVersion: sql`${User.websiteJwtVersion} + 1`,
|
||||
authTicket: "",
|
||||
})
|
||||
.where(eq(User.id, userId));
|
||||
await invalidateJwtVersionCache(userId);
|
||||
} catch (err) {
|
||||
logger.warn("Failed to revoke CMS session", {
|
||||
userId,
|
||||
error: err instanceof Error ? err.message : "Unknown",
|
||||
});
|
||||
}
|
||||
|
||||
// Revoke API bearer tokens (Sanctum / personal_access_tokens).
|
||||
try {
|
||||
const scope = personalTokenScope(userId);
|
||||
await db
|
||||
.delete(PersonalAccessTokens)
|
||||
.where(
|
||||
and(
|
||||
eq(PersonalAccessTokens.tokenableId, scope.tokenableId),
|
||||
eq(PersonalAccessTokens.tokenableType, scope.tokenableType),
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn("Failed to revoke personal access tokens", {
|
||||
userId,
|
||||
error: err instanceof Error ? err.message : "Unknown",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,40 @@ export class CmsTranslationError extends Error {
|
||||
async function bundled(locale: AppLocale): Promise<Record<string, string>> {
|
||||
return flattenObject((await import(`../messages/${locale}.json`)).default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattened catalog per locale. The dynamic import is cached by the module
|
||||
* system, but flattening 6 100 keys is not: doing that on every request cost
|
||||
* 4–12 ms of CPU per page render.
|
||||
*/
|
||||
const flatBundled = new Map<AppLocale, Promise<Record<string, string>>>();
|
||||
function bundledFlat(locale: AppLocale): Promise<Record<string, string>> {
|
||||
let pending = flatBundled.get(locale);
|
||||
if (!pending) {
|
||||
pending = bundled(locale);
|
||||
flatBundled.set(locale, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Digest of the bundled part of a locale's revision, so only overrides hash. */
|
||||
const baseDigest = new Map<AppLocale, string>();
|
||||
async function revisionFor(
|
||||
locale: AppLocale,
|
||||
overrides: Record<string, string>,
|
||||
): Promise<string> {
|
||||
let digest = baseDigest.get(locale);
|
||||
if (!digest) {
|
||||
digest = createHash("sha256")
|
||||
.update(JSON.stringify(await bundledFlat(locale)))
|
||||
.digest("hex");
|
||||
baseDigest.set(locale, digest);
|
||||
}
|
||||
return createHash("sha256")
|
||||
.update(digest)
|
||||
.update(JSON.stringify(overrides))
|
||||
.digest("hex");
|
||||
}
|
||||
async function readOverrides(file: string): Promise<Record<string, string>> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(
|
||||
@@ -65,8 +99,8 @@ export async function readCmsTranslation(
|
||||
root = defaultRoot,
|
||||
): Promise<CmsTranslationSnapshot> {
|
||||
const [base, source, overrides] = await Promise.all([
|
||||
bundled(locale),
|
||||
bundled("en"),
|
||||
bundledFlat(locale),
|
||||
bundledFlat("en"),
|
||||
readOverrides(localeFile(locale, root)),
|
||||
]);
|
||||
const messages = { ...base };
|
||||
@@ -78,9 +112,7 @@ export async function readCmsTranslation(
|
||||
}
|
||||
return {
|
||||
messages,
|
||||
revision: createHash("sha256")
|
||||
.update(JSON.stringify([base, overrides]))
|
||||
.digest("hex"),
|
||||
revision: await revisionFor(locale, overrides),
|
||||
};
|
||||
}
|
||||
export async function saveCmsTranslation(
|
||||
@@ -96,8 +128,8 @@ export async function saveCmsTranslation(
|
||||
if (current.revision !== revision)
|
||||
throw new CmsTranslationError("conflict");
|
||||
const [base, source, overrides] = await Promise.all([
|
||||
bundled(locale),
|
||||
bundled("en"),
|
||||
bundledFlat(locale),
|
||||
bundledFlat("en"),
|
||||
readOverrides(file),
|
||||
]);
|
||||
for (const [key, value] of Object.entries(changes)) {
|
||||
@@ -115,13 +147,54 @@ export async function saveCmsTranslation(
|
||||
return readCmsTranslation(locale, root);
|
||||
});
|
||||
}
|
||||
/** Per-request deduplication; runtime edits are visible on the next request. */
|
||||
interface MergedMemo {
|
||||
locale: AppLocale;
|
||||
mtimeMs: number;
|
||||
size: number;
|
||||
builtAt: number;
|
||||
tree: MessageTree;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merged tree per locale, reused across requests until the override file
|
||||
* changes. Still re-stat'ed (cheap, and at most once per MEMO_TTL_MS) so a
|
||||
* runtime translation edit stays visible without a restart.
|
||||
*/
|
||||
let mergedMemo: MergedMemo | null = null;
|
||||
const MEMO_TTL_MS = 2_000;
|
||||
|
||||
async function overrideFingerprint(
|
||||
locale: AppLocale,
|
||||
root: string,
|
||||
): Promise<{ mtimeMs: number; size: number }> {
|
||||
try {
|
||||
const stat = await fs.stat(localeFile(locale, root));
|
||||
return { mtimeMs: stat.mtimeMs, size: stat.size };
|
||||
} catch {
|
||||
return { mtimeMs: 0, size: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/** Per-request deduplication plus the cross-request memo above. */
|
||||
export const loadCmsMessages = cache(
|
||||
async (locale: AppLocale): Promise<MessageTree> => {
|
||||
const fingerprint = await overrideFingerprint(locale, defaultRoot);
|
||||
if (
|
||||
mergedMemo &&
|
||||
mergedMemo.locale === locale &&
|
||||
mergedMemo.mtimeMs === fingerprint.mtimeMs &&
|
||||
mergedMemo.size === fingerprint.size &&
|
||||
Date.now() - mergedMemo.builtAt < MEMO_TTL_MS
|
||||
) {
|
||||
return mergedMemo.tree;
|
||||
}
|
||||
|
||||
try {
|
||||
return unflattenObject(
|
||||
const tree = unflattenObject(
|
||||
(await readCmsTranslation(locale)).messages,
|
||||
) as MessageTree;
|
||||
mergedMemo = { locale, ...fingerprint, builtAt: Date.now(), tree };
|
||||
return tree;
|
||||
} catch (error) {
|
||||
logger.error("CMS translation overrides could not be loaded", {
|
||||
locale,
|
||||
|
||||
@@ -30,6 +30,23 @@ export function isValidClassname(classname: string): boolean {
|
||||
return CLASSNAME_CHAR_RE.test(classname);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asset-name safety check for values that become file names (swf / nitro / icon).
|
||||
*
|
||||
* The real rule is "cannot escape the directory": no path separators, so `../`
|
||||
* is structurally impossible. Case matters here — classnames in gamedata are
|
||||
* mixed-case (`recycler_kintsugiB`), so this must not be folded to lowercase the
|
||||
* way `isValidClassname` presumes.
|
||||
*/
|
||||
const ASSET_NAME_RE = /^[\w*.-]+$/;
|
||||
|
||||
export function isSafeAssetName(name: string): boolean {
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) return false;
|
||||
if (!ASSET_NAME_RE.test(trimmed)) return false;
|
||||
return !trimmed.includes("..");
|
||||
}
|
||||
|
||||
export const LOCAL_ICON_URL_PREFIX = "/swf/dcr/hof_furni/icons/";
|
||||
|
||||
export function getLocalIconUrl(classname: string): string {
|
||||
|
||||
+23
-20
@@ -99,6 +99,28 @@ export const loadUserPermissions = cache(async function loadUserPermissions(
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Highest rank the hotel currently has — i.e. who the dynamic owner is.
|
||||
* Rank comparisons ("can this staff member act on that user") must never be
|
||||
* hard-coded to a number, because hotels disagree on their top rank.
|
||||
* Memoised per request so several rank guards in one action cost one query.
|
||||
*/
|
||||
export const getHighestRank = cache(async (): Promise<number | null> => {
|
||||
const rows = await queryRows<{
|
||||
highest_rank: number | bigint | null;
|
||||
}>(sql`
|
||||
SELECT COALESCE(
|
||||
(
|
||||
SELECT MAX(u.\`rank\`)
|
||||
FROM users u
|
||||
INNER JOIN permission_ranks pr ON pr.id = u.\`rank\`
|
||||
),
|
||||
(SELECT MAX(id) FROM permission_ranks)
|
||||
) AS highest_rank
|
||||
`);
|
||||
return rows[0]?.highest_rank == null ? null : Number(rows[0].highest_rank);
|
||||
});
|
||||
|
||||
const getCurrentAuthorizationState = cache(async (userId: number) =>
|
||||
resolveAuthorizationState(userId, {
|
||||
user: {
|
||||
@@ -115,26 +137,7 @@ const getCurrentAuthorizationState = cache(async (userId: number) =>
|
||||
return row ?? null;
|
||||
},
|
||||
},
|
||||
highestRank: async () => {
|
||||
// Prefer the highest rank actually held by a user. Unused high IDs in
|
||||
// permission_ranks (common on Habbo DBs) would otherwise lock the real
|
||||
// owner out of super-admin / permissions management.
|
||||
const rows = await queryRows<{
|
||||
highest_rank: number | bigint | null;
|
||||
}>(sql`
|
||||
SELECT COALESCE(
|
||||
(
|
||||
SELECT MAX(u.\`rank\`)
|
||||
FROM users u
|
||||
INNER JOIN permission_ranks pr ON pr.id = u.\`rank\`
|
||||
),
|
||||
(SELECT MAX(id) FROM permission_ranks)
|
||||
) AS highest_rank
|
||||
`);
|
||||
return rows[0]?.highest_rank == null
|
||||
? null
|
||||
: Number(rows[0].highest_rank);
|
||||
},
|
||||
highestRank: async () => getHighestRank(),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,3 +16,36 @@ const CACHEABLE_ASSET_PREFIXES = ["/api/imaging/", "/api/media/"];
|
||||
export function isCacheableAssetPath(pathname: string): boolean {
|
||||
return CACHEABLE_ASSET_PREFIXES.some((prefix) => pathname.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Public pages whose anonymous rendering barely changes between visitors:
|
||||
* leaderboards, news, events, staff listing, rankings and the radio schedule.
|
||||
* These are safe to share at the edge for a few seconds while
|
||||
* stale-while-revalidate keeps the origin from seeing a stampede.
|
||||
*/
|
||||
const EDGE_CACHEABLE_PREFIXES = [
|
||||
"/leaderboard",
|
||||
"/rankings",
|
||||
"/news",
|
||||
"/staff",
|
||||
"/events",
|
||||
"/radio/schedule",
|
||||
"/community",
|
||||
"/rares",
|
||||
"/shop",
|
||||
"/badges",
|
||||
"/developers",
|
||||
"/help",
|
||||
"/guilds",
|
||||
];
|
||||
|
||||
export function isEdgeCacheablePublicPath(pathname: string): boolean {
|
||||
if (
|
||||
pathname !== "/" &&
|
||||
EDGE_CACHEABLE_PREFIXES.some(
|
||||
(p) => pathname === p || pathname.startsWith(`${p}/`),
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
+17
-5
@@ -47,12 +47,21 @@ export async function rateLimit(
|
||||
if (redis) {
|
||||
try {
|
||||
const windowKey = `ratelimit:${key}`;
|
||||
const current = await redis.incr(windowKey);
|
||||
if (current === 1) await redis.pexpire(windowKey, windowMs);
|
||||
const ttl =
|
||||
current === 1 ? windowMs : Math.max(0, await redis.pttl(windowKey));
|
||||
// One atomic round trip: INCR + PEXPIRE in a single Lua call. Two
|
||||
// separate commands left keys without a TTL whenever the process died
|
||||
// in between, which permanently locked that client out.
|
||||
const [current, ttl] = (await redis.eval(
|
||||
`local c = redis.call('INCR', KEYS[1])
|
||||
if c == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
||||
local t = redis.call('PTTL', KEYS[1])
|
||||
if t < 0 then t = tonumber(ARGV[1]) end
|
||||
return {c, t}`,
|
||||
1,
|
||||
windowKey,
|
||||
String(windowMs),
|
||||
)) as [number, number];
|
||||
if (current > limit) {
|
||||
return { ok: false, retryAfter: Math.ceil(ttl / 1000) };
|
||||
return { ok: false, retryAfter: Math.max(1, Math.ceil(ttl / 1000)) };
|
||||
}
|
||||
return { ok: true, retryAfter: 0 };
|
||||
} catch {
|
||||
@@ -64,6 +73,9 @@ export async function rateLimit(
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (redisFailWarned) {
|
||||
redisFailWarned = false;
|
||||
logger.info("[rate-limit] Redis available again — shared limits restored.");
|
||||
}
|
||||
|
||||
cleanup();
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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]));
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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 = "••••••••";
|
||||
Reference in new issue
Block a user