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
@@ -0,0 +1,25 @@
|
|||||||
|
-- Repair the escalation introduced by 0018's rule 1 ("has admin.dashboard gets
|
||||||
|
-- ALL admin.*"). Migrating 0011 grants admin.dashboard to every rank >= 6 so
|
||||||
|
-- that the sidebar opens, which meant rank 6 silently acquired
|
||||||
|
-- admin.permissions.manage, admin.rcon.execute, admin.settings.edit,
|
||||||
|
-- admin.users.edit, admin.users.reset_password, admin.room.delete, ...
|
||||||
|
--
|
||||||
|
-- Rule 1 is narrowed to `admin.%.view` (read-only, all the sidebar needs) in
|
||||||
|
-- both the migration set and the runtime repair action. This migration undoes
|
||||||
|
-- the over-grant on databases that already ran 0018: every role below the top
|
||||||
|
-- rank keeps dashboard + *.view and loses every other admin.* grant. Ranks
|
||||||
|
-- that legitimately hold tools keep them, because rule 3 only targets
|
||||||
|
-- rank >= 7 and those roles are not touched here.
|
||||||
|
|
||||||
|
DELETE `amp`
|
||||||
|
FROM `acl_model_permissions` `amp`
|
||||||
|
JOIN `acl_roles` `ar`
|
||||||
|
ON `ar`.`id` = `amp`.`model_id`
|
||||||
|
AND `ar`.`model_type` = 'Role'
|
||||||
|
AND `amp`.`model_type` = 'Role'
|
||||||
|
JOIN `acl_permissions` `ap`
|
||||||
|
ON `ap`.`id` = `amp`.`permission_id`
|
||||||
|
WHERE `ap`.`slug` LIKE 'admin.%'
|
||||||
|
AND `ap`.`slug` NOT LIKE '%.view'
|
||||||
|
AND `ar`.`slug` REGEXP '^rank_[0-9]+$'
|
||||||
|
AND CAST(SUBSTRING(`ar`.`slug`, 7) AS UNSIGNED) < 7;
|
||||||
+30
-34
@@ -4,11 +4,32 @@ import { mkdir, writeFile } from "node:fs/promises";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
|
import { validateSiteImageUpload } from "@/lib/images/site-image-upload";
|
||||||
import { MEDIA_ROOT, resolveMediaPath } from "@/lib/media-storage";
|
import { MEDIA_ROOT, resolveMediaPath } from "@/lib/media-storage";
|
||||||
import { PERMS } from "@/lib/permissions";
|
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(
|
export async function uploadMedia(
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
@@ -16,25 +37,9 @@ export async function uploadMedia(
|
|||||||
await requirePermission(PERMS.PAGES_EDIT);
|
await requirePermission(PERMS.PAGES_EDIT);
|
||||||
const file = formData.get("file") as File | null;
|
const file = formData.get("file") as File | null;
|
||||||
if (!file || file.size === 0) return { ok: false, error: "No file provided" };
|
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;
|
const stored = await storeUploadedMedia(file);
|
||||||
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
if (!stored.ok) return { ok: false, error: stored.error };
|
||||||
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));
|
|
||||||
|
|
||||||
revalidatePath("/api/media");
|
revalidatePath("/api/media");
|
||||||
revalidatePath("/admin/media");
|
revalidatePath("/admin/media");
|
||||||
@@ -45,6 +50,8 @@ export async function deleteMedia(name: string): Promise<void> {
|
|||||||
await requirePermission(PERMS.PAGES_EDIT);
|
await requirePermission(PERMS.PAGES_EDIT);
|
||||||
const { unlink } = await import("node:fs/promises");
|
const { unlink } = await import("node:fs/promises");
|
||||||
const baseDir = MEDIA_ROOT;
|
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);
|
const filePath = resolveMediaPath(name);
|
||||||
if (!filePath.startsWith(baseDir + path.sep)) return;
|
if (!filePath.startsWith(baseDir + path.sep)) return;
|
||||||
try {
|
try {
|
||||||
@@ -62,22 +69,11 @@ export async function uploadMediaAndReturn(
|
|||||||
await requirePermission(PERMS.PAGES_EDIT);
|
await requirePermission(PERMS.PAGES_EDIT);
|
||||||
const file = formData.get("file") as File | null;
|
const file = formData.get("file") as File | null;
|
||||||
if (!file || file.size === 0) return "";
|
if (!file || file.size === 0) return "";
|
||||||
if (file.size > MAX_SIZE) return "";
|
|
||||||
if (!ALLOWED.includes(file.type)) return "";
|
|
||||||
|
|
||||||
const baseDir = MEDIA_ROOT;
|
const stored = await storeUploadedMedia(file);
|
||||||
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
if (!stored.ok) return "";
|
||||||
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));
|
|
||||||
|
|
||||||
revalidatePath("/api/media");
|
revalidatePath("/api/media");
|
||||||
revalidatePath("/admin/media");
|
revalidatePath("/admin/media");
|
||||||
return `/api/media/${name}`;
|
return `/api/media/${stored.name}`;
|
||||||
}
|
}
|
||||||
@@ -14,10 +14,19 @@ import {
|
|||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { clearOfficialHabboFurnidataCache } from "@/lib/services/habbo-furnidata-cache";
|
import { clearOfficialHabboFurnidataCache } from "@/lib/services/habbo-furnidata-cache";
|
||||||
import { clearBadgeCache } from "@/lib/services/habboassets";
|
import { clearBadgeCache } from "@/lib/services/habboassets";
|
||||||
|
import {
|
||||||
|
isSecretSettingKey,
|
||||||
|
SECRET_PLACEHOLDER,
|
||||||
|
} from "@/lib/services/setting-secrets";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
const managedKeySet = new Set(MANAGED_SETTING_KEYS);
|
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 {
|
function normalizeSettingValue(key: string, value: string): string {
|
||||||
if (key === HABBO_GAMEDATA_HOTEL_SETTING_KEY) {
|
if (key === HABBO_GAMEDATA_HOTEL_SETTING_KEY) {
|
||||||
return normalizeHabboGamedataHotel(value);
|
return normalizeHabboGamedataHotel(value);
|
||||||
@@ -71,11 +80,12 @@ export async function updateSetting(formData: FormData): Promise<void> {
|
|||||||
const key = String(formData.get("key") ?? "")
|
const key = String(formData.get("key") ?? "")
|
||||||
.normalize("NFC")
|
.normalize("NFC")
|
||||||
.trim();
|
.trim();
|
||||||
const value = normalizeSettingValue(
|
const raw = String(formData.get("value") ?? "").normalize("NFC");
|
||||||
key,
|
if (!key || !RAW_SETTING_KEY_RE.test(key)) return;
|
||||||
String(formData.get("value") ?? "").normalize("NFC"),
|
// Blank on a secret means "keep what is stored", so the UI can render a
|
||||||
);
|
// placeholder without the risk of wiping the credential.
|
||||||
if (!key) return;
|
if (isSecretSettingKey(key) && raw === SECRET_PLACEHOLDER) return;
|
||||||
|
const value = isSecretSettingKey(key) ? raw : normalizeSettingValue(key, raw);
|
||||||
await db
|
await db
|
||||||
.insert(WebsiteSetting)
|
.insert(WebsiteSetting)
|
||||||
.values({ key, value })
|
.values({ key, value })
|
||||||
@@ -90,7 +100,7 @@ export async function createSetting(formData: FormData): Promise<void> {
|
|||||||
const key = String(formData.get("key") ?? "")
|
const key = String(formData.get("key") ?? "")
|
||||||
.normalize("NFC")
|
.normalize("NFC")
|
||||||
.trim()
|
.trim()
|
||||||
.slice(0, 255);
|
.slice(0, 128);
|
||||||
const value = normalizeSettingValue(
|
const value = normalizeSettingValue(
|
||||||
key,
|
key,
|
||||||
String(formData.get("value") ?? "").normalize("NFC"),
|
String(formData.get("value") ?? "").normalize("NFC"),
|
||||||
@@ -99,7 +109,17 @@ export async function createSetting(formData: FormData): Promise<void> {
|
|||||||
.normalize("NFC")
|
.normalize("NFC")
|
||||||
.trim()
|
.trim()
|
||||||
.slice(0, 255);
|
.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
|
await db
|
||||||
.insert(WebsiteSetting)
|
.insert(WebsiteSetting)
|
||||||
.values({ key, value, comment: comment || null })
|
.values({ key, value, comment: comment || null })
|
||||||
|
|||||||
@@ -41,7 +41,11 @@ const {
|
|||||||
});
|
});
|
||||||
|
|
||||||
vi.mock("@/lib/admin/guard", () => ({ requirePermission: vi.fn() }));
|
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", () => ({
|
vi.mock("@/lib/db", () => ({
|
||||||
db: {
|
db: {
|
||||||
delete: vi.fn(() => ({ where: deleteWhere })),
|
delete: vi.fn(() => ({ where: deleteWhere })),
|
||||||
@@ -109,7 +113,10 @@ beforeEach(() => {
|
|||||||
onDuplicateKeyUpdate.mockResolvedValue([{ affectedRows: 1 }]);
|
onDuplicateKeyUpdate.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
updateWhere.mockResolvedValue([{ affectedRows: 1 }]);
|
updateWhere.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
selectLimit.mockResolvedValue([]);
|
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", () => {
|
describe("bulkUnban", () => {
|
||||||
|
|||||||
+101
-32
@@ -1,6 +1,7 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { and, eq, inArray, max, sql } from "drizzle-orm";
|
import { and, eq, inArray, max, sql } from "drizzle-orm";
|
||||||
|
import { isDynamicSuperAdmin } from "@/lib/admin/authorization-policy";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import {
|
import {
|
||||||
Ban,
|
Ban,
|
||||||
@@ -11,18 +12,69 @@ import {
|
|||||||
UsersCurrency,
|
UsersCurrency,
|
||||||
UsersSettings,
|
UsersSettings,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { getHighestRank, PERMS } from "@/lib/permissions";
|
||||||
import type { ActionResult } from "@/lib/safe-action-shared";
|
import type { ActionResult } from "@/lib/safe-action-shared";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
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({
|
export async function bulkUnban({
|
||||||
userIds,
|
userIds,
|
||||||
}: {
|
}: {
|
||||||
userIds: number[];
|
userIds: number[];
|
||||||
}): Promise<ActionResult<{ unbanned: number; total: number }>> {
|
}): Promise<ActionResult<{ unbanned: number; total: number }>> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
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);
|
const unbanned = Number(result[0]?.affectedRows ?? 0);
|
||||||
await logStaffActivity({
|
await logStaffActivity({
|
||||||
staffId: staff.id,
|
staffId: staff.id,
|
||||||
@@ -30,10 +82,7 @@ export async function bulkUnban({
|
|||||||
description: `Unbanned ${unbanned} user(s)`,
|
description: `Unbanned ${unbanned} user(s)`,
|
||||||
targetType: "user",
|
targetType: "user",
|
||||||
});
|
});
|
||||||
return {
|
return { ok: true as const, data: { unbanned, total: ids.length } };
|
||||||
ok: true as const,
|
|
||||||
data: { unbanned, total: userIds.length },
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function bulkBan({
|
export async function bulkBan({
|
||||||
@@ -46,10 +95,14 @@ export async function bulkBan({
|
|||||||
duration: number;
|
duration: number;
|
||||||
}): Promise<ActionResult<{ banned: number }>> {
|
}): Promise<ActionResult<{ banned: number }>> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
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);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
let banned = 0;
|
let banned = 0;
|
||||||
|
|
||||||
for (const userId of userIds) {
|
for (const userId of ids) {
|
||||||
try {
|
try {
|
||||||
await db.insert(Ban).values({
|
await db.insert(Ban).values({
|
||||||
userId,
|
userId,
|
||||||
@@ -57,8 +110,8 @@ export async function bulkBan({
|
|||||||
machineId: "",
|
machineId: "",
|
||||||
userStaffId: staff.id,
|
userStaffId: staff.id,
|
||||||
timestamp: now,
|
timestamp: now,
|
||||||
banExpire: duration > 0 ? now + duration : 0,
|
banExpire: seconds > 0 ? now + seconds : 0,
|
||||||
banReason: reason,
|
banReason: reasonText,
|
||||||
type: "account",
|
type: "account",
|
||||||
});
|
});
|
||||||
banned++;
|
banned++;
|
||||||
@@ -92,33 +145,37 @@ export async function bulkGiveCurrency({
|
|||||||
}>
|
}>
|
||||||
> {
|
> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
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;
|
let given = 0;
|
||||||
const failedIds: Array<{ userId: number; reason: string }> = [];
|
const failedIds: Array<{ userId: number; reason: string }> = [];
|
||||||
|
|
||||||
for (const userId of userIds) {
|
for (const userId of ids) {
|
||||||
try {
|
try {
|
||||||
if (type === "credits") {
|
if (type === "credits") {
|
||||||
await db
|
await db
|
||||||
.update(User)
|
.update(User)
|
||||||
.set({ credits: sql`${User.credits} + ${amount}` })
|
.set({ credits: sql`${User.credits} + ${value}` })
|
||||||
.where(eq(User.id, userId));
|
.where(eq(User.id, userId));
|
||||||
await rcon.giveCredits(userId, amount);
|
await rcon.giveCredits(userId, value);
|
||||||
} else if (type === "pixels") {
|
} else if (type === "pixels") {
|
||||||
await db
|
await db
|
||||||
.insert(UsersCurrency)
|
.insert(UsersCurrency)
|
||||||
.values({ userId, type: 0, amount })
|
.values({ userId, type: 0, amount: value })
|
||||||
.onDuplicateKeyUpdate({
|
.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") {
|
} else if (type === "points") {
|
||||||
await db
|
await db
|
||||||
.insert(UsersCurrency)
|
.insert(UsersCurrency)
|
||||||
.values({ userId, type: 101, amount })
|
.values({ userId, type: 101, amount: value })
|
||||||
.onDuplicateKeyUpdate({
|
.onDuplicateKeyUpdate({
|
||||||
set: { amount: sql`${UsersCurrency.amount} + ${amount}` },
|
set: { amount: sql`${UsersCurrency.amount} + ${value}` },
|
||||||
});
|
});
|
||||||
await rcon.givePointsGotw(userId, amount);
|
await rcon.givePointsGotw(userId, value);
|
||||||
}
|
}
|
||||||
given++;
|
given++;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -129,7 +186,7 @@ export async function bulkGiveCurrency({
|
|||||||
await logStaffActivity({
|
await logStaffActivity({
|
||||||
staffId: staff.id,
|
staffId: staff.id,
|
||||||
action: "bulk_give_currency",
|
action: "bulk_give_currency",
|
||||||
description: `Gave ${amount} ${type} to ${given} user(s)`,
|
description: `Gave ${value} ${type} to ${given} user(s)`,
|
||||||
targetType: "user",
|
targetType: "user",
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
@@ -152,19 +209,21 @@ export async function bulkGiveBadge({
|
|||||||
}>
|
}>
|
||||||
> {
|
> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
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;
|
let given = 0;
|
||||||
const failedIds: Array<{ userId: number; reason: string }> = [];
|
const failedIds: Array<{ userId: number; reason: string }> = [];
|
||||||
|
|
||||||
for (const userId of userIds) {
|
for (const userId of ids) {
|
||||||
try {
|
try {
|
||||||
const [existing] = await db
|
const [existing] = await db
|
||||||
.select({ id: UsersBadges.id })
|
.select({ id: UsersBadges.id })
|
||||||
.from(UsersBadges)
|
.from(UsersBadges)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(eq(UsersBadges.userId, userId), eq(UsersBadges.badgeCode, code)),
|
||||||
eq(UsersBadges.userId, userId),
|
|
||||||
eq(UsersBadges.badgeCode, badgeCode),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
@@ -173,8 +232,10 @@ export async function bulkGiveBadge({
|
|||||||
.from(UsersBadges)
|
.from(UsersBadges)
|
||||||
.where(eq(UsersBadges.userId, userId));
|
.where(eq(UsersBadges.userId, userId));
|
||||||
const slotId = (agg?.maxSlot ?? 0) + 1;
|
const slotId = (agg?.maxSlot ?? 0) + 1;
|
||||||
await db.insert(UsersBadges).values({ userId, slotId, badgeCode });
|
await db
|
||||||
await rcon.giveBadge(userId, badgeCode);
|
.insert(UsersBadges)
|
||||||
|
.values({ userId, slotId, badgeCode: code });
|
||||||
|
await rcon.giveBadge(userId, code);
|
||||||
}
|
}
|
||||||
given++;
|
given++;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -211,12 +272,17 @@ export async function bulkAdjustCurrency({
|
|||||||
}>
|
}>
|
||||||
> {
|
> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
const staff = await requirePermission(PERMS.USERS_EDIT);
|
||||||
|
const ids = parseUserIds(userIds);
|
||||||
if (!Number.isFinite(amount) || amount === 0) {
|
if (!Number.isFinite(amount) || amount === 0) {
|
||||||
return { ok: false as const, error: "Amount must be a non-zero number" };
|
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) {
|
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.ok) return given;
|
||||||
if (!given.data) {
|
if (!given.data) {
|
||||||
return { ok: false as const, error: "Currency adjustment failed" };
|
return { ok: false as const, error: "Currency adjustment failed" };
|
||||||
@@ -235,7 +301,7 @@ export async function bulkAdjustCurrency({
|
|||||||
let adjusted = 0;
|
let adjusted = 0;
|
||||||
const failedIds: Array<{ userId: number; reason: string }> = [];
|
const failedIds: Array<{ userId: number; reason: string }> = [];
|
||||||
|
|
||||||
for (const userId of userIds) {
|
for (const userId of ids) {
|
||||||
try {
|
try {
|
||||||
if (type === "credits") {
|
if (type === "credits") {
|
||||||
const [user] = await db
|
const [user] = await db
|
||||||
@@ -299,8 +365,11 @@ export async function setTradeLock({
|
|||||||
untilUnix: number;
|
untilUnix: number;
|
||||||
}): Promise<ActionResult<{ userId: number; untilUnix: number }>> {
|
}): Promise<ActionResult<{ userId: number; untilUnix: number }>> {
|
||||||
const staff = await requirePermission(PERMS.USERS_EDIT);
|
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;
|
const locked = until > 0;
|
||||||
|
await guardBulkTargets(staff, [id]);
|
||||||
|
|
||||||
const [user] = await db
|
const [user] = await db
|
||||||
.select({
|
.select({
|
||||||
@@ -309,7 +378,7 @@ export async function setTradeLock({
|
|||||||
online: User.online,
|
online: User.online,
|
||||||
})
|
})
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.id, userId))
|
.where(eq(User.id, id))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return { ok: false as const, error: "User not found" };
|
return { ok: false as const, error: "User not found" };
|
||||||
@@ -331,7 +400,7 @@ export async function setTradeLock({
|
|||||||
.where(eq(Sanctions.id, existing.id));
|
.where(eq(Sanctions.id, existing.id));
|
||||||
} else {
|
} else {
|
||||||
await tx.insert(Sanctions).values({
|
await tx.insert(Sanctions).values({
|
||||||
habboId: userId,
|
habboId: id,
|
||||||
tradeLockedUntil: until,
|
tradeLockedUntil: until,
|
||||||
reason: locked ? "Trade lock (CMS)" : "",
|
reason: locked ? "Trade lock (CMS)" : "",
|
||||||
});
|
});
|
||||||
@@ -369,5 +438,5 @@ export async function setTradeLock({
|
|||||||
targetId: userId,
|
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 { PERMS } from "@/lib/permissions";
|
||||||
import { adminAction } from "@/lib/safe-action";
|
import { adminAction } from "@/lib/safe-action";
|
||||||
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
||||||
|
import { logAudit } from "@/lib/services/audit";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
|
|
||||||
const PATH = "/admin/commandocentrum";
|
const PATH = "/admin/commandocentrum";
|
||||||
|
|
||||||
const RCON_FAIL = "RCON command failed. Is the emulator running?";
|
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> {
|
async function requireRconOk(ok: boolean): Promise<void> {
|
||||||
if (!ok) throw new ActionError(RCON_FAIL);
|
if (!ok) throw new ActionError(RCON_FAIL);
|
||||||
}
|
}
|
||||||
@@ -120,9 +138,16 @@ const giveCreditsSchema = z.object({
|
|||||||
export const giveCredits = adminAction(
|
export const giveCredits = adminAction(
|
||||||
{ permission: PERMS.RCON_EXECUTE, schema: giveCreditsSchema },
|
{ permission: PERMS.RCON_EXECUTE, schema: giveCreditsSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
|
if (ctx.data.credits > MAX_CURRENCY) {
|
||||||
|
throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`);
|
||||||
|
}
|
||||||
await requireRconOk(
|
await requireRconOk(
|
||||||
await rcon.giveCredits(ctx.data.userId, ctx.data.credits),
|
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);
|
revalidatePath(PATH);
|
||||||
return actionOk();
|
return actionOk();
|
||||||
},
|
},
|
||||||
@@ -137,9 +162,16 @@ const giveAmountSchema = z.object({
|
|||||||
export const giveDuckets = adminAction(
|
export const giveDuckets = adminAction(
|
||||||
{ permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema },
|
{ permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
|
if (ctx.data.amount > MAX_CURRENCY) {
|
||||||
|
throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`);
|
||||||
|
}
|
||||||
await requireRconOk(
|
await requireRconOk(
|
||||||
await rcon.giveDuckets(ctx.data.userId, ctx.data.amount),
|
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);
|
revalidatePath(PATH);
|
||||||
return actionOk();
|
return actionOk();
|
||||||
},
|
},
|
||||||
@@ -149,9 +181,16 @@ export const giveDuckets = adminAction(
|
|||||||
export const giveDiamonds = adminAction(
|
export const giveDiamonds = adminAction(
|
||||||
{ permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema },
|
{ permission: PERMS.RCON_EXECUTE, schema: giveAmountSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
|
if (ctx.data.amount > MAX_CURRENCY) {
|
||||||
|
throw new ActionError(`Amount is too large (max ${MAX_CURRENCY})`);
|
||||||
|
}
|
||||||
await requireRconOk(
|
await requireRconOk(
|
||||||
await rcon.giveDiamonds(ctx.data.userId, ctx.data.amount),
|
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);
|
revalidatePath(PATH);
|
||||||
return actionOk();
|
return actionOk();
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,8 +10,13 @@ const state = vi.hoisted(() => ({
|
|||||||
deletes: [] as unknown[],
|
deletes: [] as unknown[],
|
||||||
affectedDelete: 1,
|
affectedDelete: 1,
|
||||||
emptyDeleteResult: false,
|
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 () => {
|
vi.mock("@/lib/db", async () => {
|
||||||
const schema = await import("@/db/schema");
|
const schema = await import("@/db/schema");
|
||||||
const { createFakeDb } = await import("@/test/fake-db");
|
const { createFakeDb } = await import("@/test/fake-db");
|
||||||
@@ -315,6 +320,18 @@ describe("sendOfflineMessage", () => {
|
|||||||
expect(redirected()).toBe("/messages?send_error=invalid");
|
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 () => {
|
it("stores an offline message for a friend", async () => {
|
||||||
state.friendships = [{ id: 1 }];
|
state.friendships = [{ id: 1 }];
|
||||||
await redirects(() =>
|
await redirects(() =>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
User,
|
User,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||||
|
import { isAllowed } from "@/lib/services/moderation";
|
||||||
|
|
||||||
type FriendOutcome =
|
type FriendOutcome =
|
||||||
| "accepted"
|
| "accepted"
|
||||||
@@ -376,6 +377,8 @@ export async function sendOfflineMessage(formData: FormData): Promise<void> {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
if (!recipient) {
|
if (!recipient) {
|
||||||
outcome = "invalid";
|
outcome = "invalid";
|
||||||
|
} else if (!(await isAllowed(message)).ok) {
|
||||||
|
outcome = "invalid";
|
||||||
} else {
|
} else {
|
||||||
await db.insert(MessengerOffline).values({
|
await db.insert(MessengerOffline).values({
|
||||||
userId: friendId,
|
userId: friendId,
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
// @ts-nocheck
|
// @ts-nocheck
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
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(),
|
selectLimit: vi.fn(),
|
||||||
insertOnDup: vi.fn().mockResolvedValue({}),
|
insertOnDup: vi.fn().mockResolvedValue({}),
|
||||||
|
selectWhere: vi.fn(() => Promise.resolve([] as Array<{ id: number }>)),
|
||||||
mockSendMail: vi.fn(),
|
mockSendMail: vi.fn(),
|
||||||
mockRedirect: vi.fn(),
|
mockRedirect: vi.fn(),
|
||||||
}),
|
}));
|
||||||
);
|
|
||||||
|
|
||||||
vi.mock("next/navigation", () => ({
|
vi.mock("next/navigation", () => ({
|
||||||
redirect: (...args: unknown[]) => {
|
redirect: (...args: unknown[]) => {
|
||||||
@@ -24,6 +24,17 @@ vi.mock("@/lib/db", () => {
|
|||||||
from: vi.fn(() => ({
|
from: vi.fn(() => ({
|
||||||
where: vi.fn(() => ({
|
where: vi.fn(() => ({
|
||||||
limit: selectLimit,
|
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", () => {
|
describe("requestReset", () => {
|
||||||
it("sends a reset email when the user exists", async () => {
|
it("sends a reset email when the user exists", async () => {
|
||||||
selectLimit.mockResolvedValue([{ id: 1 }]);
|
selectLimit.mockResolvedValue([{ id: 1 }]);
|
||||||
|
selectWhere.mockResolvedValue([{ id: 1 }]);
|
||||||
|
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.set("email", "[email protected]");
|
fd.set("email", "[email protected]");
|
||||||
|
|
||||||
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
await expect(requestReset(fd)).rejects.toThrow("redirect");
|
||||||
|
|
||||||
expect(selectLimit).toHaveBeenCalled();
|
expect(selectWhere).toHaveBeenCalled();
|
||||||
expect(insertOnDup).toHaveBeenCalled();
|
expect(insertOnDup).toHaveBeenCalled();
|
||||||
expect(mockSendMail).toHaveBeenCalledWith(
|
expect(mockSendMail).toHaveBeenCalledWith(
|
||||||
"[email protected]",
|
"[email protected]",
|
||||||
@@ -87,6 +99,7 @@ describe("requestReset", () => {
|
|||||||
|
|
||||||
it("does not send email when user is not found", async () => {
|
it("does not send email when user is not found", async () => {
|
||||||
selectLimit.mockResolvedValue([]);
|
selectLimit.mockResolvedValue([]);
|
||||||
|
selectWhere.mockResolvedValue([]);
|
||||||
|
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.set("email", "[email protected]");
|
fd.set("email", "[email protected]");
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||||
import { eq } from "drizzle-orm";
|
import { asc, eq } from "drizzle-orm";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
|
import { invalidateLoginCache } from "@/lib/auth/login-core";
|
||||||
import { hashPassword } from "@/lib/auth/password";
|
import { hashPassword } from "@/lib/auth/password";
|
||||||
|
import { revokeUserCredentials } from "@/lib/auth/session-revocation";
|
||||||
import { db, PasswordReset, User } from "@/lib/db";
|
import { db, PasswordReset, User } from "@/lib/db";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||||
import { logServerError } from "@/lib/server-log";
|
import { logServerError } from "@/lib/server-log";
|
||||||
import { captchaConfig, verifyCaptcha } from "@/lib/services/captcha";
|
import { captchaConfig, verifyCaptcha } from "@/lib/services/captcha";
|
||||||
@@ -17,6 +20,17 @@ function sha256(s: string): string {
|
|||||||
return createHash("sha256").update(s).digest("hex");
|
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> {
|
export async function requestReset(formData: FormData): Promise<void> {
|
||||||
const email = String(formData.get("email") ?? "")
|
const email = String(formData.get("email") ?? "")
|
||||||
.normalize("NFC")
|
.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.
|
// Always respond the same way so we don't reveal which emails exist.
|
||||||
if (allowed && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
if (allowed && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
|
||||||
try {
|
try {
|
||||||
const [user] = await db
|
const matches = await db
|
||||||
.select({ id: User.id })
|
.select({ id: User.id })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.mail, email))
|
.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) {
|
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 token = randomBytes(32).toString("hex");
|
||||||
const hashed = sha256(token);
|
const hashed = sha256(token);
|
||||||
const createdAt = new Date();
|
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.
|
// 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) {
|
if (!(await rateLimit(`resetpwd:${await clientIp()}`, 5, 15 * 60_000)).ok) {
|
||||||
redirect(
|
redirect(errorRedirect(email, token, "ratelimit"));
|
||||||
`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent("Too many attempts — try again later")}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let error: string | null = null;
|
let error: "password" | "invalid" | "failed" | null = null;
|
||||||
if (password.length < 12) error = "Password must be at least 12 characters";
|
if (password.length < 12) error = "password";
|
||||||
|
|
||||||
if (!error) {
|
if (!error) {
|
||||||
try {
|
try {
|
||||||
@@ -107,20 +130,29 @@ export async function resetPassword(formData: FormData): Promise<void> {
|
|||||||
row != null && a.length === b.length && timingSafeEqual(a, b);
|
row != null && a.length === b.length && timingSafeEqual(a, b);
|
||||||
|
|
||||||
if (!row || !fresh || !match) {
|
if (!row || !fresh || !match) {
|
||||||
error = "This reset link is invalid or has expired";
|
error = "invalid";
|
||||||
} else {
|
} else {
|
||||||
const [user] = await db
|
const matches = await db
|
||||||
.select({ id: User.id })
|
.select({ id: User.id })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.mail, email))
|
.where(eq(User.mail, email))
|
||||||
.limit(1);
|
.orderBy(asc(User.id));
|
||||||
|
const user = matches[0];
|
||||||
if (!user) {
|
if (!user) {
|
||||||
error = "Account not found";
|
error = "invalid";
|
||||||
} else {
|
} else {
|
||||||
await db
|
const newHash = await hashPassword(password);
|
||||||
.update(User)
|
// A password change has to end every existing session: the
|
||||||
.set({ password: await hashPassword(password) })
|
// popular reason for resetting is a compromised account, and a
|
||||||
.where(eq(User.id, user.id));
|
// 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
|
await db
|
||||||
.delete(PasswordReset)
|
.delete(PasswordReset)
|
||||||
.where(eq(PasswordReset.email, email))
|
.where(eq(PasswordReset.email, email))
|
||||||
@@ -132,14 +164,12 @@ export async function resetPassword(formData: FormData): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
error = "Could not reset the password — try again";
|
error = "failed";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
redirect(
|
redirect(errorRedirect(email, token, error));
|
||||||
`/reset?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}&error=${encodeURIComponent(error)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
redirect("/login?reset=1");
|
redirect("/login?reset=1");
|
||||||
}
|
}
|
||||||
@@ -175,8 +175,10 @@ export const setCmsPermissions = adminAction(
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-apply the same grant repair as migration 0018:
|
* Re-apply the grant repair from migration 0018/0034:
|
||||||
* - ranks with admin.dashboard get all admin.*
|
* - 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 >= 6 get admin.*.view + dashboard
|
||||||
* - ranks >= 7 get edit/manage/execute tools used by the sidebar
|
* - 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\`)
|
INSERT INTO \`acl_model_permissions\` (\`model_type\`, \`model_id\`, \`permission_id\`)
|
||||||
SELECT 'Role', ar.id, ap.id
|
SELECT 'Role', ar.id, ap.id
|
||||||
FROM \`acl_roles\` ar
|
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 (
|
WHERE EXISTS (
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM \`acl_model_permissions\` amp
|
FROM \`acl_model_permissions\` amp
|
||||||
|
|||||||
@@ -76,14 +76,17 @@ describe("rooms actions", () => {
|
|||||||
});
|
});
|
||||||
state.del.mockResolvedValue([{ affectedRows: 1 }]);
|
state.del.mockResolvedValue([{ affectedRows: 1 }]);
|
||||||
state.update.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 () => {
|
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.requirePermission).toHaveBeenCalledWith("admin.room.edit");
|
||||||
expect(state.update).toHaveBeenCalledWith(
|
expect(state.update).toHaveBeenCalledWith(
|
||||||
Items,
|
Items,
|
||||||
{ custom: "x" },
|
{ rot: 4 },
|
||||||
expect.anything(),
|
expect.anything(),
|
||||||
);
|
);
|
||||||
expect(state.logStaffActivity).toHaveBeenCalledWith(
|
expect(state.logStaffActivity).toHaveBeenCalledWith(
|
||||||
|
|||||||
+63
-20
@@ -9,16 +9,63 @@ import { rcon } from "@/lib/services/rcon";
|
|||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
import { notify } from "@/lib/services/webhook";
|
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>) {
|
export async function updateRoomItem(payload: Record<string, unknown>) {
|
||||||
const staff = await requirePermission(PERMS.ROOMS_EDIT);
|
const staff = await requirePermission(PERMS.ROOMS_EDIT);
|
||||||
const { roomId, itemId, ...data } = payload as {
|
const roomId = toPositiveInt(payload.roomId);
|
||||||
roomId: number;
|
const itemId = toPositiveInt(payload.itemId);
|
||||||
itemId: number;
|
if (!roomId || !itemId) {
|
||||||
[key: string]: unknown;
|
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
|
await db
|
||||||
.update(Items)
|
.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));
|
.where(eq(Items.id, itemId));
|
||||||
await logStaffActivity({
|
await logStaffActivity({
|
||||||
staffId: staff.id,
|
staffId: staff.id,
|
||||||
@@ -117,24 +164,20 @@ export async function deleteRoom({ id }: { id: number }) {
|
|||||||
revalidatePath("/admin/rooms");
|
revalidatePath("/admin/rooms");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateRoom({
|
export async function updateRoom({ id, ...data }: Record<string, unknown>) {
|
||||||
id,
|
|
||||||
...data
|
|
||||||
}: {
|
|
||||||
id: number;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
state?: string;
|
|
||||||
usersMax?: number;
|
|
||||||
}) {
|
|
||||||
const staff = await requirePermission(PERMS.ROOMS_EDIT);
|
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({
|
await logStaffActivity({
|
||||||
staffId: staff.id,
|
staffId: staff.id,
|
||||||
action: "room_update",
|
action: "room_update",
|
||||||
description: `Updated room #${id}`,
|
description: `Updated room #${roomId}`,
|
||||||
targetType: "room",
|
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,
|
selectQueue: [] as Queue,
|
||||||
rows: [] as Array<Record<string, unknown>>,
|
rows: [] as Array<Record<string, unknown>>,
|
||||||
failInsert: false,
|
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/cache", () => ({ revalidatePath: state.revalidatePath }));
|
||||||
vi.mock("next/navigation", () => ({
|
vi.mock("next/navigation", () => ({
|
||||||
redirect: (path: string) => {
|
redirect: (path: string) => {
|
||||||
@@ -210,6 +215,7 @@ describe("postThread", () => {
|
|||||||
state.failInsert = false;
|
state.failInsert = false;
|
||||||
state.selectQueue = [];
|
state.selectQueue = [];
|
||||||
state.rows = [];
|
state.rows = [];
|
||||||
|
state.isAllowed.mockResolvedValue({ ok: true });
|
||||||
state.transaction.mockImplementation(
|
state.transaction.mockImplementation(
|
||||||
async (fn: (tx: unknown) => Promise<unknown>, txDb: unknown) => fn(txDb),
|
async (fn: (tx: unknown) => Promise<unknown>, txDb: unknown) => fn(txDb),
|
||||||
);
|
);
|
||||||
@@ -283,6 +289,18 @@ describe("postThread", () => {
|
|||||||
expect(state.insert).not.toHaveBeenCalled();
|
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 () => {
|
it("reports not_found when the guild does not exist", async () => {
|
||||||
state.selectQueue = [[]];
|
state.selectQueue = [[]];
|
||||||
await expect(postThread(threadForm())).rejects.toThrow(
|
await expect(postThread(threadForm())).rejects.toThrow(
|
||||||
@@ -324,6 +342,7 @@ describe("replyToThread", () => {
|
|||||||
state.failInsert = false;
|
state.failInsert = false;
|
||||||
state.selectQueue = [];
|
state.selectQueue = [];
|
||||||
state.rows = [];
|
state.rows = [];
|
||||||
|
state.isAllowed.mockResolvedValue({ ok: true });
|
||||||
state.transaction.mockImplementation(
|
state.transaction.mockImplementation(
|
||||||
async (fn: (tx: unknown) => Promise<unknown>, txDb: unknown) => fn(txDb),
|
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 });
|
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 () => {
|
it("rejects missing or non-positive ids by redirecting to /guilds", async () => {
|
||||||
await expect(replyToThread(replyForm({ guildId: "abc" }))).rejects.toThrow(
|
await expect(replyToThread(replyForm({ guildId: "abc" }))).rejects.toThrow(
|
||||||
"/guilds",
|
"/guilds",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
MessengerFriendships,
|
MessengerFriendships,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
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
|
// 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
|
// 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);
|
.slice(0, MESSAGE_MAX);
|
||||||
if (!subject || !message) {
|
if (!subject || !message) {
|
||||||
outcome = "invalid";
|
outcome = "invalid";
|
||||||
|
} else if (!(await isAllowed(`${subject} ${message}`)).ok) {
|
||||||
|
outcome = "invalid";
|
||||||
} else {
|
} else {
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
@@ -326,6 +329,8 @@ export async function replyToThread(formData: FormData): Promise<void> {
|
|||||||
.slice(0, MESSAGE_MAX);
|
.slice(0, MESSAGE_MAX);
|
||||||
if (!message) {
|
if (!message) {
|
||||||
outcome = "invalid";
|
outcome = "invalid";
|
||||||
|
} else if (!(await isAllowed(message)).ok) {
|
||||||
|
outcome = "invalid";
|
||||||
} else {
|
} else {
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,22 @@ async function verifyTwoFactorCode(
|
|||||||
export async function beginTwoFactor(): Promise<void> {
|
export async function beginTwoFactor(): Promise<void> {
|
||||||
const id = await sessionUserId();
|
const id = await sessionUserId();
|
||||||
if (!env.APP_KEY) redirect("/settings/2fa?error=noappkey");
|
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 secret = generateTotpSecret();
|
||||||
const encrypted = new LaravelEncrypter(env.APP_KEY).encrypt(secret);
|
const encrypted = new LaravelEncrypter(env.APP_KEY).encrypt(secret);
|
||||||
const codes = generateRecoveryCodes();
|
const codes = generateRecoveryCodes();
|
||||||
@@ -104,12 +120,19 @@ export async function confirmTwoFactor(formData: FormData): Promise<void> {
|
|||||||
.normalize("NFC")
|
.normalize("NFC")
|
||||||
.trim();
|
.trim();
|
||||||
|
|
||||||
const { ok } = await verifyTwoFactorCode(id, code);
|
const { ok, updatedRecoveryCodes } = await verifyTwoFactorCode(id, code);
|
||||||
if (!ok) redirect("/settings/2fa?error=badcode");
|
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
|
await db
|
||||||
.update(User)
|
.update(User)
|
||||||
.set({ twoFactorConfirmedAt: new Date() })
|
.set({
|
||||||
|
twoFactorConfirmedAt: new Date(),
|
||||||
|
...(updatedRecoveryCodes !== undefined
|
||||||
|
? { twoFactorRecoveryCodes: updatedRecoveryCodes }
|
||||||
|
: {}),
|
||||||
|
})
|
||||||
.where(eq(User.id, id));
|
.where(eq(User.id, id));
|
||||||
redirect("/settings/2fa?enabled=1");
|
redirect("/settings/2fa?enabled=1");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const state = vi.hoisted(() => ({
|
|||||||
updateCall: undefined as unknown,
|
updateCall: undefined as unknown,
|
||||||
rconSetMotto: vi.fn(),
|
rconSetMotto: vi.fn(),
|
||||||
failDbUpdate: false,
|
failDbUpdate: false,
|
||||||
|
isAllowed: vi.fn(async () => ({ ok: true })),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const databaseErrorClass = vi.hoisted(
|
const databaseErrorClass = vi.hoisted(
|
||||||
@@ -63,6 +64,10 @@ vi.mock("@/lib/services/rcon", () => ({
|
|||||||
rcon: { setMotto: state.rconSetMotto },
|
rcon: { setMotto: state.rconSetMotto },
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/services/moderation", () => ({
|
||||||
|
isAllowed: state.isAllowed,
|
||||||
|
}));
|
||||||
|
|
||||||
const mockRevalidatePath = vi.hoisted(() => vi.fn());
|
const mockRevalidatePath = vi.hoisted(() => vi.fn());
|
||||||
vi.mock("next/cache", () => ({ revalidatePath: mockRevalidatePath }));
|
vi.mock("next/cache", () => ({ revalidatePath: mockRevalidatePath }));
|
||||||
|
|
||||||
@@ -98,6 +103,7 @@ beforeEach(() => {
|
|||||||
state.updateCall = undefined;
|
state.updateCall = undefined;
|
||||||
state.rconSetMotto.mockResolvedValue(true);
|
state.rconSetMotto.mockResolvedValue(true);
|
||||||
state.failDbUpdate = false;
|
state.failDbUpdate = false;
|
||||||
|
state.isAllowed.mockResolvedValue({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("updateMotto", () => {
|
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", () => {
|
describe("updateMottoAction", () => {
|
||||||
it("denies unauthenticated callers", async () => {
|
it("denies unauthenticated callers", async () => {
|
||||||
state.auth.mockResolvedValue(null);
|
state.auth.mockResolvedValue(null);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
|||||||
import { db, User } from "@/lib/db";
|
import { db, User } from "@/lib/db";
|
||||||
import { actionOk, authAction } from "@/lib/foundation/action";
|
import { actionOk, authAction } from "@/lib/foundation/action";
|
||||||
import { DatabaseError } from "@/lib/foundation/errors";
|
import { DatabaseError } from "@/lib/foundation/errors";
|
||||||
|
import { isAllowed } from "@/lib/services/moderation";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
|
|
||||||
const MOTTO_MAX = 127;
|
const MOTTO_MAX = 127;
|
||||||
@@ -16,7 +17,14 @@ const mottoSchema = z.object({
|
|||||||
.max(MOTTO_MAX, `Motto must be at most ${MOTTO_MAX} characters`),
|
.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) => {
|
const updateMottoAction = authAction({ schema: mottoSchema }, async (ctx) => {
|
||||||
|
await assertMottoAllowed(ctx.data.motto);
|
||||||
try {
|
try {
|
||||||
await db
|
await db
|
||||||
.update(User)
|
.update(User)
|
||||||
|
|||||||
@@ -62,6 +62,9 @@ vi.mock("@/lib/permissions", () => ({
|
|||||||
USERS_BAN: "users.ban",
|
USERS_BAN: "users.ban",
|
||||||
USERS_RESET_PASSWORD: "users.reset_password",
|
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", () => ({
|
vi.mock("@/lib/safe-action", () => ({
|
||||||
@@ -77,6 +80,10 @@ vi.mock("@/lib/services/audit", () => ({
|
|||||||
logAudit: vi.fn(),
|
logAudit: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/auth/session-revocation", () => ({
|
||||||
|
revokeUserCredentials: vi.fn(() => Promise.resolve()),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("@/lib/services/webhook", () => ({
|
vi.mock("@/lib/services/webhook", () => ({
|
||||||
notify: vi.fn(),
|
notify: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|||||||
+36
-5
@@ -3,8 +3,10 @@
|
|||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { isDynamicSuperAdmin } from "@/lib/admin/authorization-policy";
|
||||||
import { invalidateLoginCache } from "@/lib/auth";
|
import { invalidateLoginCache } from "@/lib/auth";
|
||||||
import { hashPassword } from "@/lib/auth/password";
|
import { hashPassword } from "@/lib/auth/password";
|
||||||
|
import { revokeUserCredentials } from "@/lib/auth/session-revocation";
|
||||||
import {
|
import {
|
||||||
Ban,
|
Ban,
|
||||||
db,
|
db,
|
||||||
@@ -13,7 +15,7 @@ import {
|
|||||||
UsersCurrency,
|
UsersCurrency,
|
||||||
UsersSettings,
|
UsersSettings,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { getHighestRank, PERMS } from "@/lib/permissions";
|
||||||
import { adminAction } from "@/lib/safe-action";
|
import { adminAction } from "@/lib/safe-action";
|
||||||
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
||||||
import { logAudit } from "@/lib/services/audit";
|
import { logAudit } from "@/lib/services/audit";
|
||||||
@@ -54,8 +56,9 @@ export const createUser = adminAction(
|
|||||||
{ permission: PERMS.USERS_EDIT, schema: createUserSchema },
|
{ permission: PERMS.USERS_EDIT, schema: createUserSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
const { username, mail, password, rank, motto } = ctx.data;
|
const { username, mail, password, rank, motto } = ctx.data;
|
||||||
|
const actorRank = ctx.session.user.rank;
|
||||||
if (rank >= ctx.session.user.rank && ctx.session.user.rank < 7) {
|
const highestRank = await getHighestRank();
|
||||||
|
if (rank >= actorRank && !isDynamicSuperAdmin(actorRank, highestRank)) {
|
||||||
throw new ActionError("Cannot assign rank equal or higher than your own");
|
throw new ActionError("Cannot assign rank equal or higher than your own");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +133,7 @@ export const updateUser = adminAction(
|
|||||||
if (
|
if (
|
||||||
userData.rank !== undefined &&
|
userData.rank !== undefined &&
|
||||||
userData.rank >= ctx.session.user.rank &&
|
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");
|
throw new ActionError("Cannot assign rank equal or higher than your own");
|
||||||
}
|
}
|
||||||
@@ -144,7 +147,15 @@ export const updateUser = adminAction(
|
|||||||
motto: string;
|
motto: string;
|
||||||
credits: number;
|
credits: number;
|
||||||
pixels: 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) {
|
if (Object.keys(patch).length > 0) {
|
||||||
await db.update(User).set(patch).where(eq(User.id, id));
|
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))
|
.where(eq(User.id, targetUserId))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (!target) throw new ActionError("User not found");
|
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");
|
throw new ActionError("Cannot modify user with equal or higher rank");
|
||||||
}
|
}
|
||||||
return target;
|
return target;
|
||||||
@@ -358,6 +376,9 @@ export const resetPassword = adminAction(
|
|||||||
.update(User)
|
.update(User)
|
||||||
.set({ password: hashed })
|
.set({ password: hashed })
|
||||||
.where(eq(User.id, ctx.data.userId));
|
.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);
|
invalidateLoginCache(target.username);
|
||||||
|
|
||||||
logAudit({
|
logAudit({
|
||||||
@@ -419,9 +440,19 @@ const alertUserSchema = z.object({
|
|||||||
export const alertUser = adminAction(
|
export const alertUser = adminAction(
|
||||||
{ permission: PERMS.USERS_EDIT, schema: alertUserSchema },
|
{ permission: PERMS.USERS_EDIT, schema: alertUserSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
|
const target = await guardRank(ctx.data.userId, ctx.session.user.rank);
|
||||||
const success = await rcon.alertUser(ctx.data.userId, ctx.data.message);
|
const success = await rcon.alertUser(ctx.data.userId, ctx.data.message);
|
||||||
if (!success)
|
if (!success)
|
||||||
throw new ActionError("Failed to send alert. Is the emulator running?");
|
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();
|
return actionOk();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -36,6 +36,11 @@ export async function resendVerification(
|
|||||||
if (!(await rateLimit(`verify:resend:${ip}`, 3, 10 * 60_000)).ok) {
|
if (!(await rateLimit(`verify:resend:${ip}`, 3, 10 * 60_000)).ok) {
|
||||||
return { ok: false, error: "rateLimited" };
|
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 {
|
try {
|
||||||
const [user] = await db
|
const [user] = await db
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export default async function ApplyStaffPage({
|
|||||||
const appliedRankIds = new Set(myApps.map((a) => a.rankId));
|
const appliedRankIds = new Set(myApps.map((a) => a.rankId));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{submitted === "1" ? (
|
{submitted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.submitted")}
|
{t("success.submitted")}
|
||||||
@@ -233,6 +233,6 @@ export default async function ApplyStaffPage({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -89,7 +89,7 @@ export default async function ApplyTeamPage({
|
|||||||
const appliedTeamIds = new Set(myApps.map((a) => a.rankId));
|
const appliedTeamIds = new Set(myApps.map((a) => a.rankId));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{submitted === "1" ? (
|
{submitted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.submitted")}
|
{t("success.submitted")}
|
||||||
@@ -199,6 +199,6 @@ export default async function ApplyTeamPage({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,7 @@ export default async function BadgesPage() {
|
|||||||
.catch(() => []);
|
.catch(() => []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🏅" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🏅" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={badges.length === 0}>
|
<ContentCard padded={badges.length === 0}>
|
||||||
@@ -76,6 +76,6 @@ export default async function BadgesPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ export default async function BannedPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main style={{ maxWidth: 560, margin: "2rem auto" }}>
|
<section style={{ maxWidth: 560, margin: "2rem auto" }}>
|
||||||
<ContentCard icon="🚫" title={t("title")} subtitle={t("subtitle")}>
|
<ContentCard icon="🚫" title={t("title")} subtitle={t("subtitle")}>
|
||||||
<p style={{ marginTop: 0 }}>{t("body")}</p>
|
<p style={{ marginTop: 0 }}>{t("body")}</p>
|
||||||
{reason ? (
|
{reason ? (
|
||||||
@@ -65,6 +65,6 @@ export default async function BannedPage() {
|
|||||||
{t("contactStaff")}
|
{t("contactStaff")}
|
||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ export default function CommunityPage() {
|
|||||||
const t = useTranslations("pages.community");
|
const t = useTranslations("pages.community");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🌍" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🌍" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<div className="card-grid sm-2 lg-3">
|
<div className="card-grid sm-2 lg-3">
|
||||||
@@ -84,6 +84,6 @@ export default function CommunityPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -398,7 +398,7 @@ export default function DevelopersPage() {
|
|||||||
const totalEndpoints = GROUPS.reduce((n, g) => n + g.endpoints.length, 0);
|
const totalEndpoints = GROUPS.reduce((n, g) => n + g.endpoints.length, 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="🧩"
|
icon="🧩"
|
||||||
title="Developer API"
|
title="Developer API"
|
||||||
@@ -479,6 +479,6 @@ export default function DevelopersPage() {
|
|||||||
</div>
|
</div>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
))}
|
))}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -102,7 +102,7 @@ export default async function DrawBadgePage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="🎨"
|
icon="🎨"
|
||||||
title="Draw a Badge"
|
title="Draw a Badge"
|
||||||
@@ -231,6 +231,6 @@ export default async function DrawBadgePage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -142,7 +142,7 @@ export default async function EventDetailPage({
|
|||||||
else if (isFull) disabledReason = t("eventFull");
|
else if (isFull) disabledReason = t("eventFull");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
<Link href="/events">{t("back")}</Link>
|
<Link href="/events">{t("back")}</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -259,6 +259,6 @@ export default async function EventDetailPage({
|
|||||||
</ul>
|
</ul>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
) : null}
|
) : null}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ async function EventsPage({
|
|||||||
const href = (page: number) =>
|
const href = (page: number) =>
|
||||||
`/events?${new URLSearchParams({ status: result?.status ?? "all", week: result?.week ?? "", mine: params.mine ?? "", page: String(page) })}`;
|
`/events?${new URLSearchParams({ status: result?.status ?? "all", week: result?.week ?? "", mine: params.mine ?? "", page: String(page) })}`;
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="📅" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="📅" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
@@ -272,7 +272,7 @@ async function EventsPage({
|
|||||||
</nav>
|
</nav>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import { requestReset } from "@/actions/password-reset";
|
import { requestReset } from "@/actions/password-reset";
|
||||||
@@ -6,6 +7,15 @@ import Link from "@/components/link";
|
|||||||
import { ContentCard } from "@/components/public/ui";
|
import { ContentCard } from "@/components/public/ui";
|
||||||
import { captchaConfig } from "@/lib/services/captcha";
|
import { captchaConfig } from "@/lib/services/captcha";
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const t = await getTranslations("pages.forgot");
|
||||||
|
return {
|
||||||
|
title: t("title"),
|
||||||
|
description: t("subtitle"),
|
||||||
|
robots: { index: false, follow: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default async function ForgotPage({
|
export default async function ForgotPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
@@ -17,12 +27,39 @@ export default async function ForgotPage({
|
|||||||
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main style={{ maxWidth: 420, margin: "2rem auto" }}>
|
<section style={{ maxWidth: 420, margin: "2rem auto" }}>
|
||||||
<ContentCard icon="🔑" title={t("title")} subtitle={t("subtitle")}>
|
<ContentCard icon="🔑" title={t("title")} subtitle={t("subtitle")}>
|
||||||
{sent ? (
|
{sent ? (
|
||||||
<p className="muted" style={{ textAlign: "center", margin: 0 }}>
|
<>
|
||||||
{t("sentNotice")}
|
<p className="muted" style={{ textAlign: "center", margin: 0 }}>
|
||||||
</p>
|
{t("sentNotice")}
|
||||||
|
</p>
|
||||||
|
{/* A mail that never arrived must be retryable from here,
|
||||||
|
otherwise the visitor is stuck on a dead end. */}
|
||||||
|
<form
|
||||||
|
action={requestReset}
|
||||||
|
style={{ display: "grid", gap: "0.7rem", marginTop: "1rem" }}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
placeholder={t("emailPlaceholder")}
|
||||||
|
autoComplete="email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<CaptchaWidget
|
||||||
|
captcha={{
|
||||||
|
provider: cfg.provider,
|
||||||
|
siteKey: cfg.siteKey || undefined,
|
||||||
|
field: cfg.field || undefined,
|
||||||
|
}}
|
||||||
|
nonce={nonce}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn btn-primary">
|
||||||
|
{t("sendAnotherLink")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<form
|
<form
|
||||||
action={requestReset}
|
action={requestReset}
|
||||||
@@ -66,6 +103,6 @@ export default async function ForgotPage({
|
|||||||
<Link href="/login">{t("backToLogin")}</Link>
|
<Link href="/login">{t("backToLogin")}</Link>
|
||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -102,7 +102,7 @@ export default async function FriendsPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{removed === "1" ? (
|
{removed === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.removed")}
|
{t("success.removed")}
|
||||||
@@ -180,6 +180,6 @@ export default async function FriendsPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -103,11 +103,11 @@ export default async function GuildForumThreadPage({
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
publicReadFailure("guild.thread")(error);
|
publicReadFailure("guild.thread")(error);
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
<PublicLoadError href={`/guilds/${guildId}/forum/${threadId}`} />
|
<PublicLoadError href={`/guilds/${guildId}/forum/${threadId}`} />
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,7 +173,7 @@ export default async function GuildForumThreadPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{replied === "1" ? (
|
{replied === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.replied")}
|
{t("success.replied")}
|
||||||
@@ -317,6 +317,6 @@ export default async function GuildForumThreadPage({
|
|||||||
{t("loginToReply")} <Link href="/login">{t("loginLink")}</Link>
|
{t("loginToReply")} <Link href="/login">{t("loginLink")}</Link>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ export default async function NewThreadPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{errorMessage ? (
|
{errorMessage ? (
|
||||||
<div role="alert" style={feedbackStyle("error")}>
|
<div role="alert" style={feedbackStyle("error")}>
|
||||||
{errorMessage}
|
{errorMessage}
|
||||||
@@ -132,6 +132,6 @@ export default async function NewThreadPage({
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -67,11 +67,11 @@ export default async function GuildForumPage({
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
publicReadFailure("guild.forum")(error);
|
publicReadFailure("guild.forum")(error);
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
<PublicLoadError href={`/guilds/${guildId}/forum`} />
|
<PublicLoadError href={`/guilds/${guildId}/forum`} />
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,7 +135,7 @@ export default async function GuildForumPage({
|
|||||||
const usernameById = new Map(users.map((u) => [u.id, u.username]));
|
const usernameById = new Map(users.map((u) => [u.id, u.username]));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{posted === "1" ? (
|
{posted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.posted")}
|
{t("success.posted")}
|
||||||
@@ -240,6 +240,6 @@ export default async function GuildForumPage({
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -55,11 +55,11 @@ export default async function GuildPage({
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
publicReadFailure("guild.detail")(error);
|
publicReadFailure("guild.detail")(error);
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
<PublicLoadError href={`/guilds/${guildId}`} />
|
<PublicLoadError href={`/guilds/${guildId}`} />
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +139,7 @@ export default async function GuildPage({
|
|||||||
const created = formatDate(new Date(guild.dateCreated * 1000), "date");
|
const created = formatDate(new Date(guild.dateCreated * 1000), "date");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p style={{ margin: 0 }}>
|
<p style={{ margin: 0 }}>
|
||||||
<Link href="/guilds">{t("allGuilds")}</Link>
|
<Link href="/guilds">{t("allGuilds")}</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -251,6 +251,6 @@ export default async function GuildPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ export default async function GuildsPage() {
|
|||||||
const guilds = await getGuilds();
|
const guilds = await getGuilds();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🚪" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🚪" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={!guilds?.length}>
|
<ContentCard padded={!guilds?.length}>
|
||||||
@@ -98,6 +98,6 @@ export default async function GuildsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -103,7 +103,7 @@ export default async function HelpCategoryPage({
|
|||||||
const hasButton = Boolean(cat.buttonText && cat.buttonText.trim() !== "");
|
const hasButton = Boolean(cat.buttonText && cat.buttonText.trim() !== "");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p style={{ margin: 0 }}>
|
<p style={{ margin: 0 }}>
|
||||||
<Link href="/help">{t("back")}</Link>
|
<Link href="/help">{t("back")}</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -162,6 +162,6 @@ export default async function HelpCategoryPage({
|
|||||||
</div>
|
</div>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
) : null}
|
) : null}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -127,7 +127,7 @@ export default async function HelpCenterPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="❓"
|
icon="❓"
|
||||||
title={t("title")}
|
title={t("title")}
|
||||||
@@ -278,6 +278,6 @@ export default async function HelpCenterPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -157,7 +157,7 @@ export default async function HelpTicketDetailPage({
|
|||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{replied === "1" ? (
|
{replied === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.replied")}
|
{t("success.replied")}
|
||||||
@@ -302,6 +302,6 @@ export default async function HelpTicketDetailPage({
|
|||||||
{t("closedHint")}
|
{t("closedHint")}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -67,7 +67,7 @@ export default async function HelpTicketsPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{created === "1" ? (
|
{created === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.created")}
|
{t("success.created")}
|
||||||
@@ -167,6 +167,6 @@ export default async function HelpTicketsPage({
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+12
-13
@@ -31,19 +31,18 @@ export default async function SiteLayout({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<CloudsField />
|
<CloudsField />
|
||||||
{session?.user?.id ? (
|
{/* Site chrome is public: hiding it all for anonymous visitors used to
|
||||||
<>
|
strand them — from /news, /leaderboard or /shop there was no way to
|
||||||
<div data-theme-block="top_header">
|
reach any other page at all. */}
|
||||||
<TopHeader session={session} />
|
<div data-theme-block="top_header">
|
||||||
</div>
|
<TopHeader session={session} />
|
||||||
<div data-theme-block="site_header">
|
</div>
|
||||||
<SiteHeader />
|
<div data-theme-block="site_header">
|
||||||
</div>
|
<SiteHeader />
|
||||||
<div data-theme-block="navigation">
|
</div>
|
||||||
<Navigation session={session} />
|
<div data-theme-block="navigation">
|
||||||
</div>
|
<Navigation session={session} />
|
||||||
</>
|
</div>
|
||||||
) : null}
|
|
||||||
<main>
|
<main>
|
||||||
<div
|
<div
|
||||||
data-theme-block="content_grid"
|
data-theme-block="content_grid"
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||||
import { cached } from "@/lib/cache";
|
import { cached } from "@/lib/cache";
|
||||||
import { db, User, UsersCurrency, UsersSettings } from "@/lib/db";
|
import { db, User, UsersCurrency, UsersSettings } from "@/lib/db";
|
||||||
|
import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
const t = await getTranslations("pages.leaderboard");
|
const t = await getTranslations("pages.leaderboard");
|
||||||
@@ -52,7 +53,17 @@ function formatValue(key: TabKey, value: number): string {
|
|||||||
return value.toLocaleString();
|
return value.toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
type Row = { username: string; look: string; value: number };
|
type Row = { userId: number; username: string; look: string; value: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Users who hid their wallet must not appear in the currency tabs: the profile
|
||||||
|
* page already honours that, and a leaderboard that ignores it makes the
|
||||||
|
* setting meaningless.
|
||||||
|
*/
|
||||||
|
async function withoutHiddenWallets(rows: Row[]): Promise<Row[]> {
|
||||||
|
const privacy = await loadProfilePrivacyMap(rows.map((r) => r.userId));
|
||||||
|
return rows.filter((r) => privacy.get(r.userId)?.wallet !== false);
|
||||||
|
}
|
||||||
|
|
||||||
async function loadCreditsRows(): Promise<Row[]> {
|
async function loadCreditsRows(): Promise<Row[]> {
|
||||||
try {
|
try {
|
||||||
@@ -62,6 +73,7 @@ async function loadCreditsRows(): Promise<Row[]> {
|
|||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({
|
.select({
|
||||||
|
id: User.id,
|
||||||
username: User.username,
|
username: User.username,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
credits: User.credits,
|
credits: User.credits,
|
||||||
@@ -71,11 +83,14 @@ async function loadCreditsRows(): Promise<Row[]> {
|
|||||||
.limit(20),
|
.limit(20),
|
||||||
{ staleMs: 120000 },
|
{ staleMs: 120000 },
|
||||||
);
|
);
|
||||||
return users.map((u) => ({
|
return await withoutHiddenWallets(
|
||||||
username: u.username,
|
users.map((u) => ({
|
||||||
look: u.look,
|
userId: u.id,
|
||||||
value: u.credits,
|
username: u.username,
|
||||||
}));
|
look: u.look,
|
||||||
|
value: u.credits,
|
||||||
|
})),
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -89,6 +104,7 @@ async function loadCurrencyRows(type: number): Promise<Row[]> {
|
|||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({
|
.select({
|
||||||
|
userId: User.id,
|
||||||
username: User.username,
|
username: User.username,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
value: UsersCurrency.amount,
|
value: UsersCurrency.amount,
|
||||||
@@ -99,7 +115,7 @@ async function loadCurrencyRows(type: number): Promise<Row[]> {
|
|||||||
.orderBy(desc(UsersCurrency.amount))
|
.orderBy(desc(UsersCurrency.amount))
|
||||||
.limit(20),
|
.limit(20),
|
||||||
{ staleMs: 120000 },
|
{ staleMs: 120000 },
|
||||||
);
|
).then(withoutHiddenWallets);
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
@@ -116,6 +132,7 @@ async function loadSettingsRows(
|
|||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({
|
.select({
|
||||||
|
userId: User.id,
|
||||||
username: User.username,
|
username: User.username,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
value: column,
|
value: column,
|
||||||
@@ -166,7 +183,7 @@ export default async function LeaderboardPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="📊"
|
icon="📊"
|
||||||
title={t("title")}
|
title={t("title")}
|
||||||
@@ -245,6 +262,6 @@ export default async function LeaderboardPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { count, desc, eq } from "drizzle-orm";
|
import { desc, eq } from "drizzle-orm";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
@@ -13,9 +13,11 @@ import { SurfaceCard } from "@/components/surface-card";
|
|||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { safeRedirectPath } from "@/lib/auth/safe-redirect";
|
import { safeRedirectPath } from "@/lib/auth/safe-redirect";
|
||||||
import { cached } from "@/lib/cache";
|
import { cached } from "@/lib/cache";
|
||||||
|
|
||||||
import { db, User } from "@/lib/db";
|
import { db, User } from "@/lib/db";
|
||||||
import { resolveHotelName } from "@/lib/hotel-name";
|
import { resolveHotelName } from "@/lib/hotel-name";
|
||||||
import { captchaConfig } from "@/lib/services/captcha";
|
import { captchaConfig } from "@/lib/services/captcha";
|
||||||
|
import { cachedOnlineCount } from "@/lib/services/public-counters";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
@@ -34,7 +36,11 @@ export async function generateMetadata(): Promise<Metadata> {
|
|||||||
export default async function LoginPage({
|
export default async function LoginPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
searchParams: Promise<{ from?: string; registered?: string }>;
|
searchParams: Promise<{
|
||||||
|
from?: string;
|
||||||
|
registered?: string;
|
||||||
|
reset?: string;
|
||||||
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const t = await getTranslations("pages.login");
|
const t = await getTranslations("pages.login");
|
||||||
const [hotelName, cfg, logo] = await Promise.all([
|
const [hotelName, cfg, logo] = await Promise.all([
|
||||||
@@ -53,19 +59,13 @@ export default async function LoginPage({
|
|||||||
if (session?.user?.id) redirect(redirectTo);
|
if (session?.user?.id) redirect(redirectTo);
|
||||||
|
|
||||||
const [online, recentUsers, latestUsers] = await Promise.all([
|
const [online, recentUsers, latestUsers] = await Promise.all([
|
||||||
cached("online_count", 10_000, () =>
|
cachedOnlineCount().catch(() => 0),
|
||||||
db
|
|
||||||
.select({ total: count() })
|
|
||||||
.from(User)
|
|
||||||
.where(eq(User.online, "1"))
|
|
||||||
.then((rows) => rows[0]?.total ?? 0),
|
|
||||||
).catch(() => 0),
|
|
||||||
cached(
|
cached(
|
||||||
"auth_online_users",
|
"auth_online_users",
|
||||||
10_000,
|
10_000,
|
||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({ username: User.username, look: User.look })
|
.select({ id: User.id, username: User.username, look: User.look })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.online, "1"))
|
.where(eq(User.online, "1"))
|
||||||
.limit(8),
|
.limit(8),
|
||||||
@@ -76,7 +76,7 @@ export default async function LoginPage({
|
|||||||
30_000,
|
30_000,
|
||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({ username: User.username, look: User.look })
|
.select({ id: User.id, username: User.username, look: User.look })
|
||||||
.from(User)
|
.from(User)
|
||||||
.orderBy(desc(User.accountCreated))
|
.orderBy(desc(User.accountCreated))
|
||||||
.limit(8),
|
.limit(8),
|
||||||
@@ -96,6 +96,16 @@ export default async function LoginPage({
|
|||||||
>
|
>
|
||||||
{t("registeredSuccess")}
|
{t("registeredSuccess")}
|
||||||
</p>
|
</p>
|
||||||
|
) : sp.reset === "1" ? (
|
||||||
|
// `?reset=1` comes from a successful password reset; saying so matters
|
||||||
|
// because the visitor just changed their password and a silent form
|
||||||
|
// reads like the reset failed.
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
className="auth-alert auth-alert--success animate-fade-in-up m-0 mb-4"
|
||||||
|
>
|
||||||
|
{t("passwordChanged")}
|
||||||
|
</p>
|
||||||
) : undefined;
|
) : undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export default async function LogoPage() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<main
|
<section
|
||||||
style={{
|
style={{
|
||||||
display: "grid",
|
display: "grid",
|
||||||
gap: "1.5rem",
|
gap: "1.5rem",
|
||||||
@@ -45,6 +45,6 @@ export default async function LogoPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<LogoGenerator initialText={initialText} canSaveToSite={canSaveToSite} />
|
<LogoGenerator initialText={initialText} canSaveToSite={canSaveToSite} />
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,7 @@ export default async function MaintenancePage() {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main style={{ maxWidth: 560, margin: "2rem auto" }}>
|
<section style={{ maxWidth: 560, margin: "2rem auto" }}>
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="🛠️"
|
icon="🛠️"
|
||||||
title={t("title", { hotel })}
|
title={t("title", { hotel })}
|
||||||
@@ -25,6 +25,6 @@ export default async function MaintenancePage() {
|
|||||||
{t("staffCanLogIn")}
|
{t("staffCanLogIn")}
|
||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ export default async function MarketplacePage() {
|
|||||||
const total = offers.reduce((sum, o) => sum + o.price, 0);
|
const total = offers.reduce((sum, o) => sum + o.price, 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🛍️" title={t("title")} subtitle={t("subtitle")}>
|
<ContentCard icon="🛍️" title={t("title")} subtitle={t("subtitle")}>
|
||||||
<div className="stat-grid">
|
<div className="stat-grid">
|
||||||
<StatBlock
|
<StatBlock
|
||||||
@@ -148,6 +148,6 @@ export default async function MarketplacePage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -47,14 +47,14 @@ async function MePage({
|
|||||||
data = await loadUserDashboard(userId);
|
data = await loadUserDashboard(userId);
|
||||||
} catch {
|
} catch {
|
||||||
return (
|
return (
|
||||||
<main>
|
<section>
|
||||||
<SurfaceCard className="p-6">
|
<SurfaceCard className="p-6">
|
||||||
<p role="alert">{t("loadError")}</p>
|
<p role="alert">{t("loadError")}</p>
|
||||||
<Link href="/me" className="btn btn-outline">
|
<Link href="/me" className="btn btn-outline">
|
||||||
{t("retry")}
|
{t("retry")}
|
||||||
</Link>
|
</Link>
|
||||||
</SurfaceCard>
|
</SurfaceCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Daily reward state (settings + schedule + the user's last claim). Never
|
// Daily reward state (settings + schedule + the user's last claim). Never
|
||||||
@@ -63,14 +63,14 @@ async function MePage({
|
|||||||
const user = data.userRows[0];
|
const user = data.userRows[0];
|
||||||
if (!user)
|
if (!user)
|
||||||
return (
|
return (
|
||||||
<main>
|
<section>
|
||||||
<SurfaceCard className="p-6">
|
<SurfaceCard className="p-6">
|
||||||
<p role="alert">{t("loadError")}</p>
|
<p role="alert">{t("loadError")}</p>
|
||||||
<Link href="/login" className="btn btn-outline">
|
<Link href="/login" className="btn btn-outline">
|
||||||
{t("login")}
|
{t("login")}
|
||||||
</Link>
|
</Link>
|
||||||
</SurfaceCard>
|
</SurfaceCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
const {
|
const {
|
||||||
hotelName,
|
hotelName,
|
||||||
@@ -145,7 +145,7 @@ async function MePage({
|
|||||||
? error
|
? error
|
||||||
: "error";
|
: "error";
|
||||||
return (
|
return (
|
||||||
<main className={styles.dashboard}>
|
<section className={styles.dashboard}>
|
||||||
{claimed && (
|
{claimed && (
|
||||||
<p role="status" className={styles.feedback}>
|
<p role="status" className={styles.feedback}>
|
||||||
{t("claimed")}
|
{t("claimed")}
|
||||||
@@ -181,6 +181,8 @@ async function MePage({
|
|||||||
width={100}
|
width={100}
|
||||||
height={140}
|
height={140}
|
||||||
className={styles.avatar}
|
className={styles.avatar}
|
||||||
|
loading="eager"
|
||||||
|
fetchPriority="high"
|
||||||
/>
|
/>
|
||||||
<div className={styles.identity}>
|
<div className={styles.identity}>
|
||||||
<p className="muted">{t("welcome", { hotel: hotelName })}</p>
|
<p className="muted">{t("welcome", { hotel: hotelName })}</p>
|
||||||
@@ -469,7 +471,7 @@ async function MePage({
|
|||||||
</SurfaceCard>
|
</SurfaceCard>
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ export default async function MessagesPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{accepted === "1" ? (
|
{accepted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.accepted")}
|
{t("success.accepted")}
|
||||||
@@ -391,6 +391,6 @@ export default async function MessagesPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -94,7 +94,7 @@ async function ArticlePage({
|
|||||||
} catch {
|
} catch {
|
||||||
logger.error("Public article lookup failed", { module: "news" });
|
logger.error("Public article lookup failed", { module: "news" });
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="📰" title={t("loadError")}>
|
<ContentCard icon="📰" title={t("loadError")}>
|
||||||
<p role="alert">{t("loadError")}</p>
|
<p role="alert">{t("loadError")}</p>
|
||||||
<a
|
<a
|
||||||
@@ -104,7 +104,7 @@ async function ArticlePage({
|
|||||||
{t("retry")}
|
{t("retry")}
|
||||||
</a>
|
</a>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (!article) notFound();
|
if (!article) notFound();
|
||||||
@@ -159,7 +159,7 @@ async function ArticlePage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{comment === "posted" ? (
|
{comment === "posted" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.posted")}
|
{t("success.posted")}
|
||||||
@@ -196,7 +196,16 @@ async function ArticlePage({
|
|||||||
src={article.image}
|
src={article.image}
|
||||||
alt=""
|
alt=""
|
||||||
decoding="async"
|
decoding="async"
|
||||||
style={{ width: "100%", borderRadius: 10, margin: "0 0 1rem" }}
|
loading="eager"
|
||||||
|
// Reserve the box: an unbounded hero image shifts the whole
|
||||||
|
// article down once the bitmap decodes.
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
aspectRatio: "16 / 9",
|
||||||
|
objectFit: "cover",
|
||||||
|
borderRadius: 10,
|
||||||
|
margin: "0 0 1rem",
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{/* Article body is rich HTML (atom uses TinyMCE) — sanitised server-side. */}
|
{/* Article body is rich HTML (atom uses TinyMCE) — sanitised server-side. */}
|
||||||
@@ -414,7 +423,7 @@ async function ArticlePage({
|
|||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ async function NewsPage({
|
|||||||
`/news?${new URLSearchParams({ q: result?.search ?? params.q ?? "", order: result?.order ?? "newest", page: String(page) })}`;
|
`/news?${new URLSearchParams({ q: result?.search ?? params.q ?? "", order: result?.order ?? "newest", page: String(page) })}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="📰" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="📰" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
@@ -186,7 +186,7 @@ async function NewsPage({
|
|||||||
</nav>
|
</nav>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-10
@@ -1,4 +1,4 @@
|
|||||||
import { count, desc, eq } from "drizzle-orm";
|
import { desc, eq } from "drizzle-orm";
|
||||||
import { ArrowRight, ChevronDown } from "lucide-react";
|
import { ArrowRight, ChevronDown } from "lucide-react";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
@@ -25,7 +25,9 @@ import { formatDate } from "@/lib/format-date";
|
|||||||
import { resolveHotelName } from "@/lib/hotel-name";
|
import { resolveHotelName } from "@/lib/hotel-name";
|
||||||
import { captchaConfig } from "@/lib/services/captcha";
|
import { captchaConfig } from "@/lib/services/captcha";
|
||||||
import { getNewsList } from "@/lib/services/news-list";
|
import { getNewsList } from "@/lib/services/news-list";
|
||||||
|
import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy";
|
||||||
import {
|
import {
|
||||||
|
cachedOnlineCount,
|
||||||
countArticles,
|
countArticles,
|
||||||
countPhotos,
|
countPhotos,
|
||||||
countRooms,
|
countRooms,
|
||||||
@@ -183,13 +185,7 @@ async function getHotelData() {
|
|||||||
recentUsers,
|
recentUsers,
|
||||||
recentPhotos,
|
recentPhotos,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
cached("online_count", 10_000, () =>
|
cachedOnlineCount().catch(publicReadFailure("home.online")),
|
||||||
db
|
|
||||||
.select({ total: count() })
|
|
||||||
.from(User)
|
|
||||||
.where(eq(User.online, "1"))
|
|
||||||
.then((rows) => rows[0]?.total ?? 0),
|
|
||||||
).catch(publicReadFailure("home.online")),
|
|
||||||
cached("total_users", 300_000, countUsers, { staleMs: 300000 }).catch(
|
cached("total_users", 300_000, countUsers, { staleMs: 300000 }).catch(
|
||||||
publicReadFailure("home.users"),
|
publicReadFailure("home.users"),
|
||||||
),
|
),
|
||||||
@@ -210,7 +206,7 @@ async function getHotelData() {
|
|||||||
15_000,
|
15_000,
|
||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({ username: User.username, look: User.look })
|
.select({ id: User.id, username: User.username, look: User.look })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.online, "1"))
|
.where(eq(User.online, "1"))
|
||||||
.limit(12),
|
.limit(12),
|
||||||
@@ -259,11 +255,22 @@ export default async function Home() {
|
|||||||
totalPhotos,
|
totalPhotos,
|
||||||
articleCount,
|
articleCount,
|
||||||
articles,
|
articles,
|
||||||
recentUsers,
|
recentUsers: rawRecentUsers,
|
||||||
recentPhotos,
|
recentPhotos,
|
||||||
logo,
|
logo,
|
||||||
} = await getHotelData();
|
} = await getHotelData();
|
||||||
|
|
||||||
|
// Users who hide their online state must not surface in the "who is online"
|
||||||
|
// rails on the homepage either.
|
||||||
|
const recentUserPrivacy = await loadProfilePrivacyMap(
|
||||||
|
(rawRecentUsers ?? []).map((u) => u.id),
|
||||||
|
);
|
||||||
|
const recentUsers =
|
||||||
|
rawRecentUsers === null
|
||||||
|
? null
|
||||||
|
: rawRecentUsers.filter(
|
||||||
|
(u) => recentUserPrivacy.get(u.id)?.online !== false,
|
||||||
|
);
|
||||||
const captcha = await captchaConfig();
|
const captcha = await captchaConfig();
|
||||||
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { ContentCard, EmptyState } from "@/components/public/ui";
|
|||||||
import { cached } from "@/lib/cache";
|
import { cached } from "@/lib/cache";
|
||||||
import { CameraWeb, db } from "@/lib/db";
|
import { CameraWeb, db } from "@/lib/db";
|
||||||
import { formatDate } from "@/lib/format-date";
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy";
|
||||||
import { publicReadFailure } from "@/lib/services/public-read";
|
import { publicReadFailure } from "@/lib/services/public-read";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
@@ -53,9 +54,16 @@ export default async function PhotosPage() {
|
|||||||
photos = publicReadFailure("photos")(error);
|
photos = publicReadFailure("photos")(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Users can hide their photos everywhere, not only on their profile.
|
||||||
|
const photoOwners = [...new Set((photos ?? []).map((p) => p.userId))];
|
||||||
|
const photoPrivacy = await loadProfilePrivacyMap(photoOwners);
|
||||||
|
const visiblePhotos = (photos ?? []).filter(
|
||||||
|
(p) => photoPrivacy.get(p.userId)?.photos !== false,
|
||||||
|
);
|
||||||
|
|
||||||
// Pre-shape for the client lightbox: translate captions server-side so the
|
// Pre-shape for the client lightbox: translate captions server-side so the
|
||||||
// client component stays free of i18n/db dependencies.
|
// client component stays free of i18n/db dependencies.
|
||||||
const items: LightboxPhoto[] = (photos ?? []).map((p) => ({
|
const items: LightboxPhoto[] = visiblePhotos.map((p) => ({
|
||||||
id: String(p.id),
|
id: String(p.id),
|
||||||
url: p.url,
|
url: p.url,
|
||||||
alt: t("photoAlt", { id: p.userId }),
|
alt: t("photoAlt", { id: p.userId }),
|
||||||
@@ -64,7 +72,7 @@ export default async function PhotosPage() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="📸" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="📸" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={items.length === 0}>
|
<ContentCard padded={items.length === 0}>
|
||||||
@@ -76,6 +84,6 @@ export default async function PhotosPage() {
|
|||||||
<PhotoLightbox photos={items} />
|
<PhotoLightbox photos={items} />
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -96,7 +96,7 @@ export default async function PollDetailPage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
<Link href="/polls">{t("back")}</Link>
|
<Link href="/polls">{t("back")}</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -248,6 +248,6 @@ export default async function PollDetailPage({
|
|||||||
</div>
|
</div>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
) : null}
|
) : null}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -60,7 +60,7 @@ export default async function PollsPage() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="📊" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="📊" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={polls.length === 0}>
|
<ContentCard padded={polls.length === 0}>
|
||||||
@@ -122,6 +122,6 @@ export default async function PollsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,7 @@ export default async function RadioApplyPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{submitted === "1" ? (
|
{submitted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.submitted")}
|
{t("success.submitted")}
|
||||||
@@ -199,6 +199,6 @@ export default async function RadioApplyPage({
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -33,7 +33,7 @@ export default async function RadioContestDetailPage({
|
|||||||
const active = contest.isActive ? "Active" : "Ended";
|
const active = contest.isActive ? "Active" : "Ended";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
<Link href="/radio/contests">← Back to contests</Link>
|
<Link href="/radio/contests">← Back to contests</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -90,6 +90,6 @@ export default async function RadioContestDetailPage({
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ export default async function RadioContestsPage() {
|
|||||||
.catch(() => []);
|
.catch(() => []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🎉" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🎉" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={contests.length === 0}>
|
<ContentCard padded={contests.length === 0}>
|
||||||
@@ -71,6 +71,6 @@ export default async function RadioContestsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -38,7 +38,7 @@ export default async function RadioGiveawayDetailPage({
|
|||||||
: null);
|
: null);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
<p className="muted" style={{ margin: 0 }}>
|
||||||
<Link href="/radio/giveaways">← Back to giveaways</Link>
|
<Link href="/radio/giveaways">← Back to giveaways</Link>
|
||||||
</p>
|
</p>
|
||||||
@@ -95,6 +95,6 @@ export default async function RadioGiveawayDetailPage({
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ export default async function RadioGiveawaysPage() {
|
|||||||
.catch(() => []);
|
.catch(() => []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🎁" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🎁" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={giveaways.length === 0}>
|
<ContentCard padded={giveaways.length === 0}>
|
||||||
@@ -78,6 +78,6 @@ export default async function RadioGiveawaysPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -38,7 +38,7 @@ export default async function RadioLeaderboardPage() {
|
|||||||
const rows = await loadRows();
|
const rows = await loadRows();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🏆" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🏆" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={rows.length === 0}>
|
<ContentCard padded={rows.length === 0}>
|
||||||
@@ -85,6 +85,6 @@ export default async function RadioLeaderboardPage() {
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -120,7 +120,7 @@ export default async function RadioPage() {
|
|||||||
const isLive = Boolean(streamUrl);
|
const isLive = Boolean(streamUrl);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{/* ── Header: live stream + now playing ─────────────────────── */}
|
{/* ── Header: live stream + now playing ─────────────────────── */}
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon="📻"
|
icon="📻"
|
||||||
@@ -262,6 +262,6 @@ export default async function RadioPage() {
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ export default async function RadioSchedulePage() {
|
|||||||
const hasAny = schedules.length > 0;
|
const hasAny = schedules.length > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🗓️" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🗓️" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={!hasAny}>
|
<ContentCard padded={!hasAny}>
|
||||||
@@ -126,6 +126,6 @@ export default async function RadioSchedulePage() {
|
|||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -73,7 +73,7 @@ export default async function RadioShoutsPage({
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{posted === "1" ? (
|
{posted === "1" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.posted")}
|
{t("success.posted")}
|
||||||
@@ -166,6 +166,6 @@ export default async function RadioShoutsPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,7 @@ export default async function RankingsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🏆" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🏆" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<ContentCard padded={!users?.length}>
|
<ContentCard padded={!users?.length}>
|
||||||
@@ -104,6 +104,6 @@ export default async function RankingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -96,7 +96,7 @@ export default async function RareCategoryPage({
|
|||||||
badgeBase && cat.badge ? `${badgeBase}/${cat.badge}.gif` : "";
|
badgeBase && cat.badge ? `${badgeBase}/${cat.badge}.gif` : "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard
|
<ContentCard
|
||||||
icon={badgeSrc ? undefined : "💎"}
|
icon={badgeSrc ? undefined : "💎"}
|
||||||
title={
|
title={
|
||||||
@@ -194,6 +194,6 @@ export default async function RareCategoryPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,7 @@ export default async function RareValuesPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="💎" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="💎" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
{categories.length === 0 ? (
|
{categories.length === 0 ? (
|
||||||
@@ -116,6 +116,6 @@ export default async function RareValuesPage() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ export default async function RedeemPage() {
|
|||||||
if (!user) redirect("/login");
|
if (!user) redirect("/login");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="🎟️" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="🎟️" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
<div className="card-grid sm-2">
|
<div className="card-grid sm-2">
|
||||||
@@ -63,6 +63,6 @@ export default async function RedeemPage() {
|
|||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { count, desc, eq } from "drizzle-orm";
|
import { desc, eq } from "drizzle-orm";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
@@ -12,9 +12,11 @@ import { RegisterForm } from "@/components/auth/register-form";
|
|||||||
import { SurfaceCard } from "@/components/surface-card";
|
import { SurfaceCard } from "@/components/surface-card";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { cached } from "@/lib/cache";
|
import { cached } from "@/lib/cache";
|
||||||
|
|
||||||
import { db, User } from "@/lib/db";
|
import { db, User } from "@/lib/db";
|
||||||
import { resolveHotelName } from "@/lib/hotel-name";
|
import { resolveHotelName } from "@/lib/hotel-name";
|
||||||
import { captchaConfig } from "@/lib/services/captcha";
|
import { captchaConfig } from "@/lib/services/captcha";
|
||||||
|
import { cachedOnlineCount } from "@/lib/services/public-counters";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
@@ -42,19 +44,13 @@ export default async function RegisterPage() {
|
|||||||
if (session?.user?.id) redirect("/me");
|
if (session?.user?.id) redirect("/me");
|
||||||
|
|
||||||
const [online, recentUsers, latestUsers] = await Promise.all([
|
const [online, recentUsers, latestUsers] = await Promise.all([
|
||||||
cached("online_count", 10_000, () =>
|
cachedOnlineCount().catch(() => 0),
|
||||||
db
|
|
||||||
.select({ total: count() })
|
|
||||||
.from(User)
|
|
||||||
.where(eq(User.online, "1"))
|
|
||||||
.then((rows) => rows[0]?.total ?? 0),
|
|
||||||
).catch(() => 0),
|
|
||||||
cached(
|
cached(
|
||||||
"auth_online_users",
|
"auth_online_users",
|
||||||
10_000,
|
10_000,
|
||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({ username: User.username, look: User.look })
|
.select({ id: User.id, username: User.username, look: User.look })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.online, "1"))
|
.where(eq(User.online, "1"))
|
||||||
.limit(8),
|
.limit(8),
|
||||||
@@ -65,7 +61,7 @@ export default async function RegisterPage() {
|
|||||||
30_000,
|
30_000,
|
||||||
() =>
|
() =>
|
||||||
db
|
db
|
||||||
.select({ username: User.username, look: User.look })
|
.select({ id: User.id, username: User.username, look: User.look })
|
||||||
.from(User)
|
.from(User)
|
||||||
.orderBy(desc(User.accountCreated))
|
.orderBy(desc(User.accountCreated))
|
||||||
.limit(8),
|
.limit(8),
|
||||||
|
|||||||
@@ -1,8 +1,26 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import { resetPassword } from "@/actions/password-reset";
|
import { resetPassword } from "@/actions/password-reset";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { ContentCard } from "@/components/public/ui";
|
import { ContentCard } from "@/components/public/ui";
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const t = await getTranslations("pages.reset");
|
||||||
|
return {
|
||||||
|
title: t("title"),
|
||||||
|
description: t("subtitle"),
|
||||||
|
// Single-use links: never indexable.
|
||||||
|
robots: { index: false, follow: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ERROR_KEYS: Record<string, string> = {
|
||||||
|
password: "passwordMinLength",
|
||||||
|
ratelimit: "tooManyAttempts",
|
||||||
|
invalid: "invalidLink",
|
||||||
|
failed: "failed",
|
||||||
|
};
|
||||||
|
|
||||||
export default async function ResetPage({
|
export default async function ResetPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
@@ -10,9 +28,12 @@ export default async function ResetPage({
|
|||||||
}) {
|
}) {
|
||||||
const t = await getTranslations("pages.reset");
|
const t = await getTranslations("pages.reset");
|
||||||
const { email = "", token = "", error } = await searchParams;
|
const { email = "", token = "", error } = await searchParams;
|
||||||
|
// Only codes the action can produce are mapped — anything else stays silent
|
||||||
|
// instead of being echoed back onto our own domain.
|
||||||
|
const errorKey = error ? (ERROR_KEYS[error] ?? null) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main style={{ maxWidth: 420, margin: "2rem auto" }}>
|
<section style={{ maxWidth: 420, margin: "2rem auto" }}>
|
||||||
<ContentCard icon="🔐" title={t("title")} subtitle={t("subtitle")}>
|
<ContentCard icon="🔐" title={t("title")} subtitle={t("subtitle")}>
|
||||||
<form action={resetPassword} style={{ display: "grid", gap: "0.7rem" }}>
|
<form action={resetPassword} style={{ display: "grid", gap: "0.7rem" }}>
|
||||||
<input type="hidden" name="email" value={email} />
|
<input type="hidden" name="email" value={email} />
|
||||||
@@ -28,15 +49,16 @@ export default async function ResetPage({
|
|||||||
{t("resetPassword")}
|
{t("resetPassword")}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
{error ? (
|
{errorKey ? (
|
||||||
<p
|
<p
|
||||||
|
role="alert"
|
||||||
style={{
|
style={{
|
||||||
color: "var(--color-danger)",
|
color: "var(--color-danger)",
|
||||||
textAlign: "center",
|
textAlign: "center",
|
||||||
marginBottom: 0,
|
marginBottom: 0,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{error}
|
{t(errorKey)}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
<p
|
<p
|
||||||
@@ -46,6 +68,6 @@ export default async function ResetPage({
|
|||||||
<Link href="/login">{t("backToLogin")}</Link>
|
<Link href="/login">{t("backToLogin")}</Link>
|
||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -101,7 +101,7 @@ export default async function RoomPage({
|
|||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<p style={{ margin: 0 }}>
|
<p style={{ margin: 0 }}>
|
||||||
<Link href="/" className="btn btn-outline">
|
<Link href="/" className="btn btn-outline">
|
||||||
← Back to the hotel
|
← Back to the hotel
|
||||||
@@ -166,6 +166,6 @@ export default async function RoomPage({
|
|||||||
Enter the hotel to visit {room.name || `room #${room.id}`} in 3D.
|
Enter the hotel to visit {room.name || `room #${room.id}`} in 3D.
|
||||||
</EmptyState>
|
</EmptyState>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import { LocalEventTime } from "@/components/public/local-event-time";
|
|||||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||||
import { withPublicPagePerformance } from "@/lib/public-page-performance";
|
import { withPublicPagePerformance } from "@/lib/public-page-performance";
|
||||||
|
import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy";
|
||||||
import { loadPublicSearch } from "@/lib/services/public-search";
|
import { loadPublicSearch } from "@/lib/services/public-search";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
@@ -29,6 +30,11 @@ async function SearchPage({ searchParams }: { searchParams: Promise<Params> }) {
|
|||||||
eventsPage: Number(params.eventsPage ?? 1),
|
eventsPage: Number(params.eventsPage ?? 1),
|
||||||
});
|
});
|
||||||
const query = result?.query ?? "";
|
const query = result?.query ?? "";
|
||||||
|
// Users who hide their online state must not have it surfaced here either —
|
||||||
|
// the listing, not just the profile, is what makes it enumerable.
|
||||||
|
const userRows =
|
||||||
|
result?.users.status === "fulfilled" ? result.users.value.rows : [];
|
||||||
|
const userPrivacy = await loadProfilePrivacyMap(userRows.map((u) => u.id));
|
||||||
const pagination = (
|
const pagination = (
|
||||||
kind: "users" | "rooms" | "news" | "events",
|
kind: "users" | "rooms" | "news" | "events",
|
||||||
data: { page: number; lastPage: number; total: number },
|
data: { page: number; lastPage: number; total: number },
|
||||||
@@ -65,7 +71,7 @@ async function SearchPage({ searchParams }: { searchParams: Promise<Params> }) {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard title={t("title")} subtitle={t("subtitle")} icon="🔎" />
|
<ContentCard title={t("title")} subtitle={t("subtitle")} icon="🔎" />
|
||||||
<ContentCard>
|
<ContentCard>
|
||||||
<form
|
<form
|
||||||
@@ -119,7 +125,12 @@ async function SearchPage({ searchParams }: { searchParams: Promise<Params> }) {
|
|||||||
{user.username}
|
{user.username}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs muted">
|
<span className="text-xs muted">
|
||||||
{t(user.online === "1" ? "online" : "offline")}
|
{t(
|
||||||
|
user.online === "1" &&
|
||||||
|
userPrivacy.get(user.id)?.online !== false
|
||||||
|
? "online"
|
||||||
|
: "offline",
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
@@ -220,7 +231,7 @@ async function SearchPage({ searchParams }: { searchParams: Promise<Params> }) {
|
|||||||
</section>
|
</section>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export default async function TwoFactorPage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main
|
<section
|
||||||
style={{
|
style={{
|
||||||
display: "grid",
|
display: "grid",
|
||||||
gap: "1.5rem",
|
gap: "1.5rem",
|
||||||
@@ -149,6 +149,11 @@ export default async function TwoFactorPage({
|
|||||||
{t("rateLimit")}
|
{t("rateLimit")}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
{sp.error === "alreadyenabled" ? (
|
||||||
|
<p style={{ color: "var(--color-danger)", marginTop: 0 }}>
|
||||||
|
{t("alreadyEnabled")}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{!hasAppKey ? (
|
{!hasAppKey ? (
|
||||||
<p style={{ margin: 0 }}>
|
<p style={{ margin: 0 }}>
|
||||||
@@ -217,6 +222,6 @@ export default async function TwoFactorPage({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -78,7 +78,7 @@ export default async function SessionsPage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{signedOutAll === "1" ? (
|
{signedOutAll === "1" ? (
|
||||||
<p
|
<p
|
||||||
role="status"
|
role="status"
|
||||||
@@ -169,6 +169,6 @@ export default async function SessionsPage({
|
|||||||
</table>
|
</table>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
) : null}
|
) : null}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ export default async function ShopPage({
|
|||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
{boughtMessage ? (
|
{boughtMessage ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{boughtMessage}
|
{boughtMessage}
|
||||||
@@ -340,6 +340,6 @@ export default async function ShopPage({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ export default async function TopUpPage({
|
|||||||
const rate = creditsPerUnit();
|
const rate = creditsPerUnit();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<section className="page-grid">
|
||||||
<ContentCard icon="💳" title={t("title")} subtitle={t("subtitle")} />
|
<ContentCard icon="💳" title={t("title")} subtitle={t("subtitle")} />
|
||||||
|
|
||||||
{sp.status === "cancel" ? (
|
{sp.status === "cancel" ? (
|
||||||
@@ -92,6 +92,6 @@ export default async function TopUpPage({
|
|||||||
</p>
|
</p>
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,7 @@ export default async function StaffPage() {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className={styles.page}>
|
<section className={styles.page}>
|
||||||
<SurfaceCard className={styles.hero}>
|
<SurfaceCard className={styles.hero}>
|
||||||
<div>
|
<div>
|
||||||
<h1>{t("title")}</h1>
|
<h1>{t("title")}</h1>
|
||||||
@@ -151,6 +151,6 @@ export default async function StaffPage() {
|
|||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -338,7 +338,7 @@ async function ProfilePage({
|
|||||||
const badgeByCode = new Map(badgeDetails.map((b) => [b.badgeKey, b]));
|
const badgeByCode = new Map(badgeDetails.map((b) => [b.badgeKey, b]));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className={`page-grid ${styles.profile}`}>
|
<section className={`page-grid ${styles.profile}`}>
|
||||||
{friend === "sent" ? (
|
{friend === "sent" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.sent")}
|
{t("success.sent")}
|
||||||
@@ -373,6 +373,8 @@ async function ProfilePage({
|
|||||||
width={100}
|
width={100}
|
||||||
height={150}
|
height={150}
|
||||||
className={styles.avatar}
|
className={styles.avatar}
|
||||||
|
loading="eager"
|
||||||
|
fetchPriority="high"
|
||||||
/>
|
/>
|
||||||
<div className={styles.identity}>
|
<div className={styles.identity}>
|
||||||
<h1 style={{ margin: "0 0 0.25rem" }}>{user.username}</h1>
|
<h1 style={{ margin: "0 0 0.25rem" }}>{user.username}</h1>
|
||||||
@@ -692,7 +694,7 @@ async function ProfilePage({
|
|||||||
</ContentCard>
|
</ContentCard>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { eq } from "drizzle-orm";
|
import { asc, eq } from "drizzle-orm";
|
||||||
import { CheckCircle2, Clock, MailX } from "lucide-react";
|
import { CheckCircle2, Clock, MailX } from "lucide-react";
|
||||||
|
import type { Metadata } from "next";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import { ResendVerificationForm } from "@/components/auth/resend-verification-form";
|
import { ResendVerificationForm } from "@/components/auth/resend-verification-form";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
@@ -7,6 +8,16 @@ import { SurfaceCard } from "@/components/surface-card";
|
|||||||
import { isValidVerificationToken } from "@/lib/auth/email-verification";
|
import { isValidVerificationToken } from "@/lib/auth/email-verification";
|
||||||
import { db, User } from "@/lib/db";
|
import { db, User } from "@/lib/db";
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const t = await getTranslations("pages.verify");
|
||||||
|
return {
|
||||||
|
title: t("verifiedTitle"),
|
||||||
|
description: t("invalidSubtitle"),
|
||||||
|
// Token links are single-use; the page itself has nothing to index.
|
||||||
|
robots: { index: false, follow: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
type Status = "verified" | "already" | "invalid" | "unavailable";
|
type Status = "verified" | "already" | "invalid" | "unavailable";
|
||||||
|
|
||||||
function StatusCard({
|
function StatusCard({
|
||||||
@@ -31,7 +42,7 @@ function StatusCard({
|
|||||||
const tint = tintMap[color] ?? tintMap.blue;
|
const tint = tintMap[color] ?? tintMap.blue;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="flex min-h-[60vh] items-center justify-center px-4">
|
<section className="flex min-h-[60vh] items-center justify-center px-4">
|
||||||
<SurfaceCard className="w-full max-w-md">
|
<SurfaceCard className="w-full max-w-md">
|
||||||
<div
|
<div
|
||||||
className="flex items-center gap-2.5 border-b px-5 py-4"
|
className="flex items-center gap-2.5 border-b px-5 py-4"
|
||||||
@@ -76,7 +87,7 @@ function StatusCard({
|
|||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
</SurfaceCard>
|
</SurfaceCard>
|
||||||
</main>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,11 +109,14 @@ export default async function VerifyPage({
|
|||||||
const ok = await isValidVerificationToken(normalisedEmail, token);
|
const ok = await isValidVerificationToken(normalisedEmail, token);
|
||||||
if (ok) {
|
if (ok) {
|
||||||
try {
|
try {
|
||||||
const [user] = await db
|
// Legacy databases allow duplicate addresses; always resolve the
|
||||||
|
// oldest account so the link cannot verify a different one.
|
||||||
|
const matches = await db
|
||||||
.select({ id: User.id, mailVerified: User.mailVerified })
|
.select({ id: User.id, mailVerified: User.mailVerified })
|
||||||
.from(User)
|
.from(User)
|
||||||
.where(eq(User.mail, normalisedEmail))
|
.where(eq(User.mail, normalisedEmail))
|
||||||
.limit(1);
|
.orderBy(asc(User.id));
|
||||||
|
const user = matches[0];
|
||||||
if (!user) {
|
if (!user) {
|
||||||
status = "invalid";
|
status = "invalid";
|
||||||
} else if (user.mailVerified === "1") {
|
} else if (user.mailVerified === "1") {
|
||||||
@@ -173,6 +187,21 @@ export default async function VerifyPage({
|
|||||||
<p className="text-sm" style={{ color: "var(--color-text-muted)" }}>
|
<p className="text-sm" style={{ color: "var(--color-text-muted)" }}>
|
||||||
{t("unavailableBody")}
|
{t("unavailableBody")}
|
||||||
</p>
|
</p>
|
||||||
|
{/* Transient failure: offer both the retry path and the way out
|
||||||
|
instead of leaving the visitor stranded on this card. */}
|
||||||
|
<ResendVerificationForm />
|
||||||
|
<Link
|
||||||
|
href="/login"
|
||||||
|
className={`${linkClass} !shadow-none`}
|
||||||
|
style={{
|
||||||
|
background: "transparent",
|
||||||
|
color: "var(--color-text-readable)",
|
||||||
|
border:
|
||||||
|
"2px solid color-mix(in srgb, var(--color-text-muted) 20%, transparent)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("backToLogin")}
|
||||||
|
</Link>
|
||||||
</StatusCard>
|
</StatusCard>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
|
import { AdminToaster } from "@/components/admin/admin-toaster";
|
||||||
import { NitroCleanupPanel } from "@/components/admin/studio/nitro-cleanup-panel";
|
import { NitroCleanupPanel } from "@/components/admin/studio/nitro-cleanup-panel";
|
||||||
|
|
||||||
export default function HousekeepingHotelNitroCleanupPage() {
|
export default function HousekeepingHotelNitroCleanupPage() {
|
||||||
return <NitroCleanupPanel />;
|
return (
|
||||||
|
<>
|
||||||
|
<NitroCleanupPanel />
|
||||||
|
<AdminToaster />
|
||||||
|
</>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ import type { ReactNode } from "react";
|
|||||||
import { AdminHubChrome } from "@/components/admin/admin-hub-chrome";
|
import { AdminHubChrome } from "@/components/admin/admin-hub-chrome";
|
||||||
import { AdminMobileWrapper } from "@/components/admin/admin-mobile-wrapper";
|
import { AdminMobileWrapper } from "@/components/admin/admin-mobile-wrapper";
|
||||||
import { AdminSidebarNav } from "@/components/admin/admin-sidebar-nav";
|
import { AdminSidebarNav } from "@/components/admin/admin-sidebar-nav";
|
||||||
|
import { AdminToaster } from "@/components/admin/admin-toaster";
|
||||||
import { AdminTopbar } from "@/components/admin/admin-topbar";
|
import { AdminTopbar } from "@/components/admin/admin-topbar";
|
||||||
import { LanguageSwitcher } from "@/components/language-switcher";
|
import { LanguageSwitcher } from "@/components/language-switcher";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
@@ -54,6 +55,7 @@ export default async function AdminLayout({
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</AdminMobileWrapper>
|
</AdminMobileWrapper>
|
||||||
|
<AdminToaster />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ function parsePageParams(
|
|||||||
) {
|
) {
|
||||||
const sp = new URLSearchParams(rawParams);
|
const sp = new URLSearchParams(rawParams);
|
||||||
const parsed = parseListParams(sp);
|
const parsed = parseListParams(sp);
|
||||||
const perPage = Number(rawParams.perPage) || defaultPerPage;
|
// parseListParams clamps perPage to 1..100 — use it instead of the raw value.
|
||||||
|
const perPage = parsed.perPage || defaultPerPage;
|
||||||
return { search: parsed.search.trim(), page: parsed.page, perPage };
|
return { search: parsed.search.trim(), page: parsed.page, perPage };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,8 +64,10 @@ async function loadLogList<RawRow, Row>(
|
|||||||
rawParams,
|
rawParams,
|
||||||
input.defaultPerPage ?? 50,
|
input.defaultPerPage ?? 50,
|
||||||
);
|
);
|
||||||
const offset = (page - 1) * perPage;
|
// Cap the offset: `?page=1000000` otherwise builds a multi-hundred-million
|
||||||
const like = `%${search}%`;
|
// row scan before returning an empty page.
|
||||||
|
const offset = Math.min((page - 1) * perPage, 100_000);
|
||||||
|
const like = `%${search.slice(0, 100)}%`;
|
||||||
const where = search ? sql`WHERE ${spec.searchWhere(like)}` : sql``;
|
const where = search ? sql`WHERE ${spec.searchWhere(like)}` : sql``;
|
||||||
|
|
||||||
const [rawRowsResult, countRows] = await Promise.all([
|
const [rawRowsResult, countRows] = await Promise.all([
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { StatusCard } from "@/components/admin/dashboard";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { db, WebsiteSetting } from "@/lib/db";
|
import { db, WebsiteSetting } from "@/lib/db";
|
||||||
|
|
||||||
type Field = { key: string; comment: string };
|
type Field = { key: string; comment: string; secret?: boolean };
|
||||||
type Group = { title: string; fields: Field[] };
|
type Group = { title: string; fields: Field[] };
|
||||||
|
|
||||||
const GROUPS: Group[] = [
|
const GROUPS: Group[] = [
|
||||||
@@ -19,7 +19,11 @@ const GROUPS: Group[] = [
|
|||||||
{ key: "radio_stream_backup_url", comment: "Backup stream URL" },
|
{ key: "radio_stream_backup_url", comment: "Backup stream URL" },
|
||||||
{ key: "radio_azurecast_base_url", comment: "AzureCast base URL" },
|
{ key: "radio_azurecast_base_url", comment: "AzureCast base URL" },
|
||||||
{ key: "radio_azurecast_station_id", comment: "AzureCast station ID" },
|
{ key: "radio_azurecast_station_id", comment: "AzureCast station ID" },
|
||||||
{ key: "radio_azurecast_api_key", comment: "AzureCast API key" },
|
{
|
||||||
|
key: "radio_azurecast_api_key",
|
||||||
|
comment: "AzureCast API key",
|
||||||
|
secret: true,
|
||||||
|
},
|
||||||
{ key: "radio_azurecast_port", comment: "AzureCast stream port" },
|
{ key: "radio_azurecast_port", comment: "AzureCast stream port" },
|
||||||
{
|
{
|
||||||
key: "radio_azurecast_protocol",
|
key: "radio_azurecast_protocol",
|
||||||
@@ -41,9 +45,14 @@ const GROUPS: Group[] = [
|
|||||||
{
|
{
|
||||||
key: "radio_sambroadcaster_password",
|
key: "radio_sambroadcaster_password",
|
||||||
comment: "Sambroadcaster password",
|
comment: "Sambroadcaster password",
|
||||||
|
secret: true,
|
||||||
},
|
},
|
||||||
{ key: "radio_virtual_dj_url", comment: "Virtual DJ URL" },
|
{ key: "radio_virtual_dj_url", comment: "Virtual DJ URL" },
|
||||||
{ key: "radio_virtual_dj_password", comment: "Virtual DJ password" },
|
{
|
||||||
|
key: "radio_virtual_dj_password",
|
||||||
|
comment: "Virtual DJ password",
|
||||||
|
secret: true,
|
||||||
|
},
|
||||||
{ key: "radio_djs_api_url", comment: "DJs API URL" },
|
{ key: "radio_djs_api_url", comment: "DJs API URL" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -331,7 +340,11 @@ const GROUPS: Group[] = [
|
|||||||
{
|
{
|
||||||
title: "Discord webhook & custom code",
|
title: "Discord webhook & custom code",
|
||||||
fields: [
|
fields: [
|
||||||
{ key: "radio_discord_webhook_url", comment: "Discord webhook URL" },
|
{
|
||||||
|
key: "radio_discord_webhook_url",
|
||||||
|
comment: "Discord webhook URL",
|
||||||
|
secret: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: "radio_discord_enabled",
|
key: "radio_discord_enabled",
|
||||||
comment: "Enable Discord notifications (0=no, 1=yes)",
|
comment: "Enable Discord notifications (0=no, 1=yes)",
|
||||||
@@ -467,7 +480,15 @@ export default async function AdminRadioSettingsPage() {
|
|||||||
<input
|
<input
|
||||||
id={`f_${field.key}`}
|
id={`f_${field.key}`}
|
||||||
name={field.key}
|
name={field.key}
|
||||||
defaultValue={values.get(field.key) ?? ""}
|
// Credentials are masked and blank means "keep".
|
||||||
|
type={field.secret ? "password" : "text"}
|
||||||
|
autoComplete="off"
|
||||||
|
placeholder={
|
||||||
|
field.secret ? "Leave blank to keep" : undefined
|
||||||
|
}
|
||||||
|
defaultValue={
|
||||||
|
field.secret ? "" : (values.get(field.key) ?? "")
|
||||||
|
}
|
||||||
style={{ width: "100%" }}
|
style={{ width: "100%" }}
|
||||||
/>
|
/>
|
||||||
{field.comment ? (
|
{field.comment ? (
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import { MANAGED_SETTING_KEYS } from "./cms-settings-config";
|
|||||||
|
|
||||||
interface SettingRow {
|
interface SettingRow {
|
||||||
key: string;
|
key: string;
|
||||||
|
/** Masked for secrets — the real value never reaches the client. */
|
||||||
value: string;
|
value: string;
|
||||||
comment: string | null;
|
comment: string | null;
|
||||||
|
secret?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AdvancedSettingsPanel({
|
export function AdvancedSettingsPanel({
|
||||||
@@ -126,7 +128,7 @@ export function AdvancedSettingsPanel({
|
|||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<code className="flex-1 text-xs break-all text-muted-foreground">
|
<code className="flex-1 text-xs break-all text-muted-foreground">
|
||||||
{s.value}
|
{s.secret ? "•• hidden ••" : s.value}
|
||||||
</code>
|
</code>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import { getTranslations } from "next-intl/server";
|
|||||||
import { AdminPageShell } from "@/components/admin/admin-page-shell";
|
import { AdminPageShell } from "@/components/admin/admin-page-shell";
|
||||||
import { db, WebsiteSetting } from "@/lib/db";
|
import { db, WebsiteSetting } from "@/lib/db";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
|
import {
|
||||||
|
isSecretSettingKey,
|
||||||
|
SECRET_PLACEHOLDER,
|
||||||
|
} from "@/lib/services/setting-secrets";
|
||||||
import { AdvancedSettingsPanel } from "./advanced-settings-panel";
|
import { AdvancedSettingsPanel } from "./advanced-settings-panel";
|
||||||
import { FIELD_DEFAULTS, MANAGED_SETTING_KEYS } from "./cms-settings-config";
|
import { FIELD_DEFAULTS, MANAGED_SETTING_KEYS } from "./cms-settings-config";
|
||||||
import { CmsSettingsForm } from "./cms-settings-form";
|
import { CmsSettingsForm } from "./cms-settings-form";
|
||||||
@@ -61,10 +65,14 @@ export default async function AdminSettings() {
|
|||||||
<CmsSettingsForm values={values} canEdit={canEdit} />
|
<CmsSettingsForm values={values} canEdit={canEdit} />
|
||||||
|
|
||||||
<AdvancedSettingsPanel
|
<AdvancedSettingsPanel
|
||||||
|
// Credentials never leave the server: a reader with only
|
||||||
|
// SETTINGS_VIEW must not receive captcha/radio secrets in the
|
||||||
|
// payload, and an editor sees a "keep stored value" placeholder.
|
||||||
settings={settings.map((s) => ({
|
settings={settings.map((s) => ({
|
||||||
key: s.key,
|
key: s.key,
|
||||||
value: s.value,
|
value: isSecretSettingKey(s.key) ? SECRET_PLACEHOLDER : s.value,
|
||||||
comment: s.comment,
|
comment: s.comment,
|
||||||
|
secret: isSecretSettingKey(s.key),
|
||||||
}))}
|
}))}
|
||||||
canEdit={canEdit}
|
canEdit={canEdit}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { invalidateCatalogTotals } from "@/features/catalog/server/catalog-total
|
|||||||
import { apiError, apiOk } from "@/lib/api";
|
import { apiError, apiOk } from "@/lib/api";
|
||||||
import { withAdmin } from "@/lib/api-handler";
|
import { withAdmin } from "@/lib/api-handler";
|
||||||
import { db, ItemsBase, queryRows } from "@/lib/db";
|
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 { localFurnitureStatus } from "@/lib/furni/local-presence";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { logAudit } from "@/lib/services/audit";
|
import { logAudit } from "@/lib/services/audit";
|
||||||
@@ -709,9 +709,20 @@ export const PATCH = withAdmin(
|
|||||||
[];
|
[];
|
||||||
|
|
||||||
for (const item of items) {
|
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 =
|
const baseClassname =
|
||||||
starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname;
|
starIdx !== -1 ? normalised.substring(0, starIdx) : normalised;
|
||||||
const nitroPath = path.join(
|
const nitroPath = path.join(
|
||||||
/*turbopackIgnore: true*/ nitroDir,
|
/*turbopackIgnore: true*/ nitroDir,
|
||||||
`${baseClassname}.nitro`,
|
`${baseClassname}.nitro`,
|
||||||
|
|||||||
@@ -6,11 +6,20 @@ import { PERMS } from "@/lib/permissions";
|
|||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
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(
|
export const POST = withAdmin(
|
||||||
{ permission: PERMS.USERS_EDIT },
|
{ permission: PERMS.USERS_EDIT },
|
||||||
async (request, context) => {
|
async (request, context) => {
|
||||||
const staffId = context.session.user.id;
|
const staffId = context.session.user.id;
|
||||||
const staffRank = context.session.user.rank;
|
const staffRank = context.session.user.rank;
|
||||||
|
const isSuper = context.permissions.isSuperAdmin;
|
||||||
const formData = await request.formData();
|
const formData = await request.formData();
|
||||||
const userId = Number(formData.get("userId"));
|
const userId = Number(formData.get("userId"));
|
||||||
const username = String(formData.get("username") || "");
|
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") {
|
if (action === "set_rank") {
|
||||||
const rank = Number(formData.get("rank") || "0");
|
const rank = Number(formData.get("rank") || "0");
|
||||||
if (!Number.isInteger(rank) || rank < 1) {
|
if (!Number.isInteger(rank) || rank < 1) {
|
||||||
@@ -141,7 +177,7 @@ export const POST = withAdmin(
|
|||||||
|
|
||||||
if (action === "give_credits") {
|
if (action === "give_credits") {
|
||||||
const credits = Number(formData.get("credits") || "0");
|
const credits = Number(formData.get("credits") || "0");
|
||||||
if (!credits || credits <= 0) {
|
if (!positiveAmount(credits)) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, message: "Invalid credit amount" },
|
{ success: false, message: "Invalid credit amount" },
|
||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
@@ -166,7 +202,7 @@ export const POST = withAdmin(
|
|||||||
|
|
||||||
if (action === "give_duckets") {
|
if (action === "give_duckets") {
|
||||||
const amount = Number(formData.get("amount") || "0");
|
const amount = Number(formData.get("amount") || "0");
|
||||||
if (!amount || amount <= 0) {
|
if (!positiveAmount(amount)) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, message: "Invalid duckets amount" },
|
{ success: false, message: "Invalid duckets amount" },
|
||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
@@ -188,7 +224,7 @@ export const POST = withAdmin(
|
|||||||
|
|
||||||
if (action === "give_diamonds") {
|
if (action === "give_diamonds") {
|
||||||
const amount = Number(formData.get("amount") || "0");
|
const amount = Number(formData.get("amount") || "0");
|
||||||
if (!amount || amount <= 0) {
|
if (!positiveAmount(amount)) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, message: "Invalid diamonds amount" },
|
{ success: false, message: "Invalid diamonds amount" },
|
||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
@@ -213,7 +249,7 @@ export const POST = withAdmin(
|
|||||||
|
|
||||||
if (action === "give_points") {
|
if (action === "give_points") {
|
||||||
const amount = Number(formData.get("amount") || "0");
|
const amount = Number(formData.get("amount") || "0");
|
||||||
if (!amount || amount <= 0) {
|
if (!positiveAmount(amount)) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, message: "Invalid points amount" },
|
{ success: false, message: "Invalid points amount" },
|
||||||
{ status: 400 },
|
{ status: 400 },
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ export async function POST(request: Request) {
|
|||||||
!request.headers.get("content-type")?.startsWith("application/json")
|
!request.headers.get("content-type")?.startsWith("application/json")
|
||||||
)
|
)
|
||||||
return new Response(null, { status: 403 });
|
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);
|
const limit = await rateLimit(`cms-error:${await clientIp()}`, 20, 60000);
|
||||||
if (!limit.ok) return new Response(null, { status: 429 });
|
if (!limit.ok) return new Response(null, { status: 429 });
|
||||||
const reader = request.body?.getReader();
|
const reader = request.body?.getReader();
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
import { and, count, desc, eq, or, sql } from "drizzle-orm";
|
|
||||||
import { env } from "@/env";
|
import { env } from "@/env";
|
||||||
import { apiJson } from "@/lib/api";
|
import { apiJson } from "@/lib/api";
|
||||||
import { db, User, WebsiteArticles } from "@/lib/db";
|
|
||||||
import { resolveHotelName } from "@/lib/hotel-name";
|
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
import { apiCacheKey, cacheSafe } from "@/lib/redis-cache";
|
import { cachedHomePayload } from "@/lib/services/home-payload";
|
||||||
import { cacheNews } from "@/lib/services/news-cache";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/home — combined landing payload: the latest 4 website_articles and
|
* 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) {
|
export async function GET(_req: Request) {
|
||||||
try {
|
try {
|
||||||
const data = await cacheNews(apiCacheKey("home"), 15_000, async () => {
|
return apiJson(await cachedHomePayload());
|
||||||
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);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error("Public news query failed", { module: "news", error });
|
logger.error("Public news query failed", { module: "news", error });
|
||||||
return apiJson(
|
return apiJson(
|
||||||
|
|||||||
@@ -14,11 +14,29 @@ const CURRENCY_TYPE: Record<Exclude<LeaderboardType, "credits">, number> = {
|
|||||||
duckets: 0,
|
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[]> {
|
async function loadCreditsRows(): Promise<Row[]> {
|
||||||
const users = await db
|
const users = await db
|
||||||
.select({
|
.select({
|
||||||
|
userId: User.id,
|
||||||
username: User.username,
|
username: User.username,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
credits: User.credits,
|
credits: User.credits,
|
||||||
@@ -26,8 +44,9 @@ async function loadCreditsRows(): Promise<Row[]> {
|
|||||||
.from(User)
|
.from(User)
|
||||||
.orderBy(desc(User.credits))
|
.orderBy(desc(User.credits))
|
||||||
.limit(20);
|
.limit(20);
|
||||||
return users.map((u, i) => ({
|
return (await withoutHiddenWallets(users)).map((u, i) => ({
|
||||||
rank: i + 1,
|
rank: i + 1,
|
||||||
|
userId: u.userId,
|
||||||
username: u.username,
|
username: u.username,
|
||||||
look: u.look,
|
look: u.look,
|
||||||
value: u.credits,
|
value: u.credits,
|
||||||
@@ -55,15 +74,24 @@ async function loadCurrencyRows(type: number): Promise<Row[]> {
|
|||||||
top.map((t) => t.userId),
|
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) => {
|
.map((t) => {
|
||||||
const u = byId.get(t.userId);
|
const u = byId.get(t.userId);
|
||||||
if (!u) return null;
|
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 }));
|
.map((r, i) => ({ rank: i + 1, ...r }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
import { existsSync, readdirSync, statSync } from "node:fs";
|
import { existsSync, readdirSync, statSync } from "node:fs";
|
||||||
import { resolve } from "node:path";
|
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 { 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;
|
const dir = MEDIA_ROOT;
|
||||||
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
||||||
if (!existsSync(dir)) {
|
if (!existsSync(dir)) {
|
||||||
return NextResponse.json({ files: [] });
|
return apiOk({ files: [] });
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
// eslint-disable-next-line security/detect-non-literal-fs-filename
|
||||||
const files = readdirSync(dir)
|
const files = readdirSync(dir)
|
||||||
@@ -23,5 +30,5 @@ export async function GET() {
|
|||||||
})
|
})
|
||||||
.sort((a, b) => b.uploaded - a.uploaded);
|
.sort((a, b) => b.uploaded - a.uploaded);
|
||||||
|
|
||||||
return NextResponse.json({ files });
|
return apiOk({ files });
|
||||||
}
|
});
|
||||||
@@ -31,8 +31,20 @@ export async function GET(req: Request) {
|
|||||||
.limit(take)
|
.limit(take)
|
||||||
.offset(skip),
|
.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({
|
return cacheSafe({
|
||||||
data: photos,
|
data: photos.filter(
|
||||||
|
(p) => photoPrivacy.get(p.userId)?.photos !== false,
|
||||||
|
),
|
||||||
meta: {
|
meta: {
|
||||||
page,
|
page,
|
||||||
perPage,
|
perPage,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { bearerUserId } from "@/lib/api-auth";
|
|||||||
import { db, RadioShouts, User } from "@/lib/db";
|
import { db, RadioShouts, User } from "@/lib/db";
|
||||||
import { rateLimit } from "@/lib/rate-limit";
|
import { rateLimit } from "@/lib/rate-limit";
|
||||||
import { apiCacheKey, redisCache } from "@/lib/redis-cache";
|
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
|
// 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
|
// 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 {
|
try {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
await db.insert(RadioShouts).values({
|
await db.insert(RadioShouts).values({
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export async function GET(
|
|||||||
async () => {
|
async () => {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.select({
|
.select({
|
||||||
|
id: User.id,
|
||||||
username: User.username,
|
username: User.username,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
motto: User.motto,
|
motto: User.motto,
|
||||||
@@ -39,13 +40,21 @@ export async function GET(
|
|||||||
return null;
|
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({
|
return cacheSafe({
|
||||||
username: row.username,
|
username: row.username,
|
||||||
look: row.look,
|
look: row.look,
|
||||||
motto: row.motto,
|
motto: row.motto,
|
||||||
rank: row.rank,
|
rank: row.rank,
|
||||||
credits: row.credits,
|
credits: privacy.values.wallet ? row.credits : null,
|
||||||
online: row.online === "1",
|
online: privacy.values.online ? row.online === "1" : null,
|
||||||
accountCreated: row.accountCreated,
|
accountCreated: row.accountCreated,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|||||||
+3
-10
@@ -1,12 +1,11 @@
|
|||||||
import { count, eq } from "drizzle-orm";
|
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { issueSsoTicket } from "@/lib/auth/sso-ticket";
|
import { issueSsoTicket } from "@/lib/auth/sso-ticket";
|
||||||
import { cached } from "@/lib/cache";
|
|
||||||
import { resolveClientIp } from "@/lib/client-ip";
|
import { resolveClientIp } from "@/lib/client-ip";
|
||||||
import { db, User } from "@/lib/db";
|
|
||||||
import { resolveHotelName } from "@/lib/hotel-name";
|
import { resolveHotelName } from "@/lib/hotel-name";
|
||||||
|
import { cachedOnlineCount } from "@/lib/services/public-counters";
|
||||||
|
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
import { ClientView } from "./client-view";
|
import { ClientView } from "./client-view";
|
||||||
|
|
||||||
@@ -27,13 +26,7 @@ export default async function ClientPage() {
|
|||||||
// render as fast as possible since the player is waiting for the game.
|
// render as fast as possible since the player is waiting for the game.
|
||||||
const [ticket, onlineCount] = await Promise.all([
|
const [ticket, onlineCount] = await Promise.all([
|
||||||
issueSsoTicket(userId, hotelName, ip),
|
issueSsoTicket(userId, hotelName, ip),
|
||||||
cached("online_count", 10_000, async () => {
|
cachedOnlineCount().catch(() => 0),
|
||||||
const [row] = await db
|
|
||||||
.select({ total: count() })
|
|
||||||
.from(User)
|
|
||||||
.where(eq(User.online, "1"));
|
|
||||||
return row?.total ?? 0;
|
|
||||||
}).catch(() => 0),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -167,6 +167,61 @@ html {
|
|||||||
text-size-adjust: 100%;
|
text-size-adjust: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Route transition (CSS only — no animation runtime on public pages) ── */
|
||||||
|
@keyframes page-enter-rise {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translate3d(0, 10px, 0);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.page-enter {
|
||||||
|
animation: page-enter-rise 240ms ease-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Route progress indicator ─────────────────────────────────────────── */
|
||||||
|
.route-progress {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0 0 auto 0;
|
||||||
|
z-index: 99999;
|
||||||
|
height: 3px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: transparent;
|
||||||
|
pointer-events: none;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 200ms linear;
|
||||||
|
}
|
||||||
|
.route-progress[data-loading="true"] {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
@keyframes route-progress-run {
|
||||||
|
from {
|
||||||
|
width: 0%;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
70% {
|
||||||
|
width: 85%;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
width: 100%;
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.route-progress__bar {
|
||||||
|
display: block;
|
||||||
|
height: 100%;
|
||||||
|
width: 0;
|
||||||
|
background: var(--color-primary);
|
||||||
|
box-shadow: 0 0 10px var(--color-primary);
|
||||||
|
}
|
||||||
|
.route-progress[data-loading="true"] .route-progress__bar {
|
||||||
|
animation: route-progress-run 400ms ease-in-out both;
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
html:focus-within {
|
html:focus-within {
|
||||||
scroll-behavior: auto;
|
scroll-behavior: auto;
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { NextIntlClientProvider } from "next-intl";
|
|||||||
import { getLocale, getMessages } from "next-intl/server";
|
import { getLocale, getMessages } from "next-intl/server";
|
||||||
|
|
||||||
import { type ReactNode, Suspense } from "react";
|
import { type ReactNode, Suspense } from "react";
|
||||||
import { Toaster } from "sonner";
|
|
||||||
import { GlobalProgressBar } from "@/components/global-progress-bar";
|
import { GlobalProgressBar } from "@/components/global-progress-bar";
|
||||||
import { PwaRegister } from "@/components/pwa-register";
|
import { PwaRegister } from "@/components/pwa-register";
|
||||||
import { ScopedThemeVars } from "@/components/scoped-theme-vars";
|
import { ScopedThemeVars } from "@/components/scoped-theme-vars";
|
||||||
@@ -106,19 +105,6 @@ export default async function RootLayout({
|
|||||||
<ThemeScopeDetector />
|
<ThemeScopeDetector />
|
||||||
{children}
|
{children}
|
||||||
<PwaRegister />
|
<PwaRegister />
|
||||||
<Toaster
|
|
||||||
position="top-right"
|
|
||||||
richColors
|
|
||||||
closeButton
|
|
||||||
toastOptions={{
|
|
||||||
style: {
|
|
||||||
background: "var(--color-surface)",
|
|
||||||
color: "var(--color-text-readable)",
|
|
||||||
border:
|
|
||||||
"1px solid color-mix(in srgb, var(--color-text-muted) 12%, transparent)",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</NextIntlClientProvider>
|
</NextIntlClientProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { Toaster } from "sonner";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toast host for the admin surfaces (the only place `toast()` is used). Kept out
|
||||||
|
* of the root layout so public pages don't pay for the Sonner bundle.
|
||||||
|
*/
|
||||||
|
export function AdminToaster() {
|
||||||
|
return (
|
||||||
|
<Toaster
|
||||||
|
position="top-right"
|
||||||
|
richColors
|
||||||
|
closeButton
|
||||||
|
toastOptions={{
|
||||||
|
style: {
|
||||||
|
background: "var(--color-surface)",
|
||||||
|
color: "var(--color-text-readable)",
|
||||||
|
border:
|
||||||
|
"1px solid color-mix(in srgb, var(--color-text-muted) 12%, transparent)",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,9 +3,11 @@ import { AuthTopBar } from "@/components/auth/auth-top-bar";
|
|||||||
import { Reveal } from "@/components/motion-reveal";
|
import { Reveal } from "@/components/motion-reveal";
|
||||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||||
import { SurfaceCard } from "@/components/surface-card";
|
import { SurfaceCard } from "@/components/surface-card";
|
||||||
|
import { loadProfilePrivacyMap } from "@/lib/services/profile-privacy";
|
||||||
import { ICON_FRIENDS, ICON_NAV_GOODY, ICON_NAV_ME } from "@/lib/site-icons";
|
import { ICON_FRIENDS, ICON_NAV_GOODY, ICON_NAV_ME } from "@/lib/site-icons";
|
||||||
|
|
||||||
export interface PublicUser {
|
export interface PublicUser {
|
||||||
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
look: string;
|
look: string;
|
||||||
}
|
}
|
||||||
@@ -56,22 +58,28 @@ interface AuthUsersCardsProps {
|
|||||||
* their left column. Cards with no users render nothing, so a cold database
|
* their left column. Cards with no users render nothing, so a cold database
|
||||||
* degrades to just the intro panel instead of an empty grid.
|
* degrades to just the intro panel instead of an empty grid.
|
||||||
*/
|
*/
|
||||||
export function AuthUsersCards({
|
export async function AuthUsersCards({
|
||||||
recentUsers,
|
recentUsers,
|
||||||
latestUsers,
|
latestUsers,
|
||||||
recentTitle,
|
recentTitle,
|
||||||
latestTitle,
|
latestTitle,
|
||||||
}: AuthUsersCardsProps) {
|
}: AuthUsersCardsProps) {
|
||||||
|
// "Hide my online status" must hold outside the profile too — the roster is
|
||||||
|
// exactly where that setting is worth the most.
|
||||||
|
const privacy = await loadProfilePrivacyMap(recentUsers.map((u) => u.id));
|
||||||
|
const onlineUsers = recentUsers.filter(
|
||||||
|
(u) => privacy.get(u.id)?.online !== false,
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{recentUsers.length > 0 && (
|
{onlineUsers.length > 0 && (
|
||||||
<SurfaceCard
|
<SurfaceCard
|
||||||
title={recentTitle}
|
title={recentTitle}
|
||||||
icon={ICON_NAV_GOODY}
|
icon={ICON_NAV_GOODY}
|
||||||
bodyClassName="p-4"
|
bodyClassName="p-4"
|
||||||
className="card-glow"
|
className="card-glow"
|
||||||
>
|
>
|
||||||
<AvatarGrid users={recentUsers} online />
|
<AvatarGrid users={onlineUsers} online />
|
||||||
</SurfaceCard>
|
</SurfaceCard>
|
||||||
)}
|
)}
|
||||||
{latestUsers.length > 0 && (
|
{latestUsers.length > 0 && (
|
||||||
|
|||||||
@@ -1,18 +1,19 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { motion, useIsPresent } from "motion/react";
|
|
||||||
import { usePathname, useSearchParams } from "next/navigation";
|
import { usePathname, useSearchParams } from "next/navigation";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global smooth progress indicator for page transitions.
|
* Global progress indicator for page transitions.
|
||||||
* Uses motion/react for high-performance 60fps animations.
|
*
|
||||||
|
* Driven by a CSS class instead of motion/react — the progress bar used to be
|
||||||
|
* the only reason the masonry-free public layout shipped the whole animation
|
||||||
|
* runtime to every visitor. Class names come from globals.css (`.route-progress`).
|
||||||
*/
|
*/
|
||||||
export function GlobalProgressBar() {
|
export function GlobalProgressBar() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const isPresent = useIsPresent();
|
|
||||||
|
|
||||||
// biome-ignore lint/correctness/useExhaustiveDependencies: Route changes intentionally restart the indicator timer.
|
// biome-ignore lint/correctness/useExhaustiveDependencies: Route changes intentionally restart the indicator timer.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -24,17 +25,13 @@ export function GlobalProgressBar() {
|
|||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, [pathname, searchParams]);
|
}, [pathname, searchParams]);
|
||||||
|
|
||||||
if (!isLoading && isPresent) return null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed top-0 left-0 right-0 z-[99999] h-1 bg-transparent pointer-events-none overflow-hidden">
|
<div
|
||||||
<motion.div
|
aria-hidden="true"
|
||||||
className="h-full bg-[var(--color-primary)] shadow-[0_0_10px_var(--color-primary)]"
|
data-loading={isLoading ? "true" : "false"}
|
||||||
initial={{ width: "0%", opacity: 1 }}
|
className="route-progress"
|
||||||
animate={{ width: "85%", opacity: 1 }}
|
>
|
||||||
exit={{ width: "100%", opacity: 0 }}
|
<span className="route-progress__bar" />
|
||||||
transition={{ duration: 0.3, ease: "easeInOut" }}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user