Add security middleware, audit log, alerts, PayPal, cron, radio + apps

Security (launch blockers):
- src/middleware.ts (edge): forwards x-pathname + real client IP.
- access-guard.ts (Node, from root layout): routes non-staff to /maintenance
  when maintenance mode is on, banned users to /banned. New /banned + /maintenance
  pages (the consumers the admin toggle was missing). Admin layout enforces
  force_staff_2fa before /admin.
- staff-activity.ts audit log wired into ban/lift/give-currency/set-rank actions.

Infra (parallel agents): alert service (alert_logs + Discord embed + email),
PayPal top-up (create/capture API routes + /shop/topup), cron worker
(scripts/jobs-worker.ts via croner: emulator-ping->alert, maintenance-check,
bans-cleanup), social connections page, admin radio settings/banners/ranks.
Public radio subsystem: /radio (+schedule, shouts+post, contests, giveaways,
apply, leaderboard) and /apply/staff + /apply/team submission forms. Radio nav
link added. .env.example documents the new optional vars.

(radio song-requests dropped: its table is a stub in AtomCMS — columns added by
un-modeled alter-migrations.)

Verified: tsc exit 0, vitest 48/48, next build exit 0 (82 page routes).
This commit is contained in:
Simo committed 2026-06-28 15:10:19 +02:00
1 parent e19debb795
commit 22d53d0e9c
40 files changed
+3781 -6

No files matched your search

+17 -2
View File
@@ -4,6 +4,7 @@ import { revalidatePath } from "next/cache";
import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { logStaffActivity } from "@/lib/services/staff-activity";
type BanType = "account" | "ip" | "machine" | "super";
const BAN_TYPES: ReadonlySet<string> = new Set(["account", "ip", "machine", "super"]);
@@ -40,12 +41,26 @@ export async function createBan(formData: FormData): Promise<void> {
});
if (user) await rcon.disconnectUser(userId, user.username);
await logStaffActivity({
staffId: staff.id,
action: "user_ban",
description: `Banned user #${userId} (${type}, ${hours > 0 ? `${hours}h` : "permanent"}): ${reason}`,
targetType: "user",
targetId: userId,
});
revalidatePath("/admin/bans");
}
export async function liftBan(formData: FormData): Promise<void> {
await requireStaff();
const staff = await requireStaff();
const id = Number(formData.get("id"));
if (id > 0) await prisma.ban.delete({ where: { id } });
if (id > 0) {
await prisma.ban.delete({ where: { id } });
await logStaffActivity({
staffId: staff.id,
action: "ban_lift",
description: `Lifted ban #${id}`,
});
}
revalidatePath("/admin/bans");
}
+233
View File
@@ -0,0 +1,233 @@
'use server';
import { revalidatePath } from 'next/cache';
import { requireStaff } from '@/lib/admin/guard';
import { prisma } from '@/lib/prisma';
import { siteSettings } from '@/lib/services/site-settings';
// ── Helpers ────────────────────────────────────────────────────────────────
/** Parse a FormData field into a positive BigInt id, or null when invalid. */
function parseId(raw: FormDataEntryValue | null): bigint | null {
if (typeof raw !== 'string' || raw.trim() === '') return null;
try {
const id = BigInt(raw.trim());
return id > 0n ? id : null;
} catch {
return null;
}
}
function str(raw: FormDataEntryValue | null): string {
return typeof raw === 'string' ? raw : '';
}
/** Checkbox/select truthiness: '1', 'true', 'on' → true. */
function bool(raw: FormDataEntryValue | null): boolean {
const v = str(raw).trim().toLowerCase();
return v === '1' || v === 'true' || v === 'on';
}
// ── Radio settings (website_settings radio_* keys) ─────────────────────────
/**
* Upsert one radio_* website_settings key. Mirrors AtomCMS's
* RadioSettings Filament page (key/value rows in website_settings). Busts the
* siteSettings cache so the public radio pages pick the change up immediately.
*/
export async function saveRadioSetting(formData: FormData): Promise<void> {
await requireStaff();
const key = str(formData.get('key')).trim().slice(0, 255);
const value = str(formData.get('value'));
const comment = str(formData.get('comment')).trim().slice(0, 255);
if (!key) return;
try {
await prisma.websiteSetting.upsert({
where: { key },
update: { value },
create: { key, value, comment: comment || null },
});
siteSettings.reload();
} catch {
// DB unavailable — fail soft so the action does not throw.
}
revalidatePath('/admin/radio/settings');
}
/**
* Bulk-save every radio_* field submitted by the settings form in one pass.
* The form posts a hidden `__keys` field listing the keys it rendered so we
* only touch those (and never wipe unrelated settings).
*/
export async function saveRadioSettings(formData: FormData): Promise<void> {
await requireStaff();
const keysRaw = str(formData.get('__keys'));
const keys = keysRaw
.split(',')
.map((k) => k.trim())
.filter((k) => k.startsWith('radio_') || k.startsWith('auto_dj_'));
if (keys.length === 0) return;
try {
await prisma.$transaction(
keys.map((key) => {
const value = str(formData.get(key));
return prisma.websiteSetting.upsert({
where: { key },
update: { value },
create: { key, value, comment: null },
});
}),
);
siteSettings.reload();
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/settings');
}
// ── Radio banners CRUD (radio_banners) ─────────────────────────────────────
export async function createRadioBanner(formData: FormData): Promise<void> {
const staff = await requireStaff();
const imagePath = str(formData.get('imagePath')).trim().slice(0, 255);
if (!imagePath) return;
const title = str(formData.get('title')).trim().slice(0, 255);
const description = str(formData.get('description')).trim();
const sortOrderNum = Number(str(formData.get('sortOrder')));
const sortOrder = Number.isFinite(sortOrderNum) ? Math.trunc(sortOrderNum) : 0;
const isActive = bool(formData.get('isActive'));
const now = new Date();
try {
await prisma.radioBanners.create({
data: {
userId: BigInt(staff.id),
imagePath,
title: title || null,
description: description || null,
sortOrder,
isActive,
createdAt: now,
updatedAt: now,
},
});
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/banners');
}
export async function updateRadioBanner(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
if (id === null) return;
const imagePath = str(formData.get('imagePath')).trim().slice(0, 255);
const title = str(formData.get('title')).trim().slice(0, 255);
const description = str(formData.get('description')).trim();
const sortOrderNum = Number(str(formData.get('sortOrder')));
const sortOrder = Number.isFinite(sortOrderNum) ? Math.trunc(sortOrderNum) : 0;
const isActive = bool(formData.get('isActive'));
if (!imagePath) return;
try {
await prisma.radioBanners.update({
where: { id },
data: {
imagePath,
title: title || null,
description: description || null,
sortOrder,
isActive,
updatedAt: new Date(),
},
});
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/radio/banners');
}
export async function deleteRadioBanner(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
if (id === null) return;
try {
await prisma.radioBanners.delete({ where: { id } });
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/radio/banners');
}
// ── Radio ranks CRUD (radio_ranks) ─────────────────────────────────────────
export async function createRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const name = str(formData.get('name')).trim().slice(0, 255);
if (!name) return;
const description = str(formData.get('description')).trim().slice(0, 255);
const badgeCode = str(formData.get('badgeCode')).trim().slice(0, 255);
const isActive = bool(formData.get('isActive'));
const now = new Date();
try {
await prisma.radioRanks.create({
data: {
name,
description: description || null,
badgeCode: badgeCode || null,
isActive,
createdAt: now,
updatedAt: now,
},
});
} catch {
// Fail soft.
}
revalidatePath('/admin/radio/ranks');
}
export async function updateRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
if (id === null) return;
const name = str(formData.get('name')).trim().slice(0, 255);
const description = str(formData.get('description')).trim().slice(0, 255);
const badgeCode = str(formData.get('badgeCode')).trim().slice(0, 255);
const isActive = bool(formData.get('isActive'));
if (!name) return;
try {
await prisma.radioRanks.update({
where: { id },
data: {
name,
description: description || null,
badgeCode: badgeCode || null,
isActive,
updatedAt: new Date(),
},
});
} catch {
// Row may be gone; ignore.
}
revalidatePath('/admin/radio/ranks');
}
export async function deleteRadioRank(formData: FormData): Promise<void> {
await requireStaff();
const id = parseId(formData.get('id'));
if (id === null) return;
try {
await prisma.radioRanks.delete({ where: { id } });
} catch {
// Already deleted; ignore.
}
revalidatePath('/admin/radio/ranks');
}
+17 -2
View File
@@ -5,16 +5,24 @@ import { requireStaff } from "@/lib/admin/guard";
import { prisma } from "@/lib/prisma";
import { rcon } from "@/lib/services/rcon";
import { type CurrencyName, sendCurrency } from "@/lib/services/send-currency";
import { logStaffActivity } from "@/lib/services/staff-activity";
const CURRENCIES: ReadonlySet<string> = new Set(["credits", "duckets", "diamonds", "points"]);
export async function giveCurrency(formData: FormData): Promise<void> {
await requireStaff();
const staff = await requireStaff();
const userId = Number(formData.get("userId"));
const type = String(formData.get("type"));
const amount = Number(formData.get("amount"));
if (userId > 0 && amount > 0 && CURRENCIES.has(type)) {
await sendCurrency({ rcon, db: prisma }, userId, type as CurrencyName, amount);
await logStaffActivity({
staffId: staff.id,
action: "give_currency",
description: `Gave ${amount} ${type} to user #${userId}`,
targetType: "user",
targetId: userId,
});
}
revalidatePath(`/admin/users/${userId}`);
}
@@ -31,12 +39,19 @@ export async function setMotto(formData: FormData): Promise<void> {
}
export async function setRank(formData: FormData): Promise<void> {
await requireStaff();
const staff = await requireStaff();
const userId = Number(formData.get("userId"));
const rank = Number(formData.get("rank"));
if (userId > 0 && rank > 0) {
await prisma.user.update({ where: { id: userId }, data: { rank } });
await rcon.setRank(userId, rank);
await logStaffActivity({
staffId: staff.id,
action: "rank_change",
description: `Set rank of user #${userId} to ${rank}`,
targetType: "user",
targetId: userId,
});
}
revalidatePath(`/admin/users/${userId}`);
}
+92
View File
@@ -0,0 +1,92 @@
"use server";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
// AtomCMS validates the application body with `min:10`. Mirror that floor and
// cap the write defensively (column is TEXT, but we keep applications sane).
const CONTENT_MIN = 10;
const CONTENT_MAX = 5000;
/**
* Submit a STAFF application for an open position.
*
* Faithful to AtomCMS's StaffApplicationsController@store:
* - the applicant (user_id) is re-read from the session via auth() and is
* NEVER trusted from the submitted FormData;
* - rank_id is the open position's permission id (the rank being applied for);
* - a user may only apply once per rank (idempotency guard);
* - content must be at least 10 characters.
*/
export async function applyStaff(formData: FormData): Promise<void> {
const session = await auth();
const userId = Number(session?.user?.id);
if (!Number.isInteger(userId) || userId <= 0) return;
// rank_id comes from the open position's permission_id (an Int in the schema).
const rankId = Number(formData.get("rankId"));
if (!Number.isInteger(rankId) || rankId <= 0) return;
const content = String(formData.get("content") ?? "").trim().slice(0, CONTENT_MAX);
if (content.length < CONTENT_MIN) return;
try {
// Block duplicate applications for the same rank (AtomCMS hasAppliedForPosition).
const existing = await prisma.websiteStaffApplications.findFirst({
where: { userId, rankId },
select: { id: true },
});
if (existing) return;
const now = new Date();
await prisma.websiteStaffApplications.create({
data: { userId, rankId, content, createdAt: now, updatedAt: now },
});
} catch {
// DB unavailable — fail soft; nothing to persist.
return;
}
revalidatePath("/apply/staff");
}
/**
* Submit a TEAM application.
*
* The Prisma `website_staff_applications` slice has no dedicated team column, so
* (per the conversion brief) team applications REUSE the staff-applications
* table with the team acting as the rank: rank_id carries the team id. The
* applicant is re-read from the session, never trusted from the form, and a user
* may only apply once per team.
*/
export async function applyTeam(formData: FormData): Promise<void> {
const session = await auth();
const userId = Number(session?.user?.id);
if (!Number.isInteger(userId) || userId <= 0) return;
// website_teams.id is a BigInt; rank_id on the application is an Int. The team
// id is the application's rank flag.
const rankId = Number(formData.get("teamId"));
if (!Number.isInteger(rankId) || rankId <= 0) return;
const content = String(formData.get("content") ?? "").trim().slice(0, CONTENT_MAX);
if (content.length < CONTENT_MIN) return;
try {
const existing = await prisma.websiteStaffApplications.findFirst({
where: { userId, rankId },
select: { id: true },
});
if (existing) return;
const now = new Date();
await prisma.websiteStaffApplications.create({
data: { userId, rankId, content, createdAt: now, updatedAt: now },
});
} catch {
return;
}
revalidatePath("/apply/team");
}
+65
View File
@@ -0,0 +1,65 @@
"use server";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
// Column bounds from prisma/schema.prisma (radio_applications):
// real_name VARCHAR(255); the rest are TEXT. age is an INT.
const NAME_MAX = 255;
const TEXT_MAX = 5000;
const STYLE_MAX = 5000;
function str(form: FormData, key: string, max: number): string {
return String(form.get(key) ?? "").trim().slice(0, max);
}
/**
* Submit a radio DJ application.
*
* The applicant (userId) is ALWAYS re-read from the session via auth() and is
* never taken from the submitted FormData, so a crafted form cannot file an
* application on behalf of another account. radio_applications.user_id is an
* UnsignedBigInt, hence the BigInt() coercion.
*/
export async function applyDj(formData: FormData): Promise<void> {
const session = await auth();
const userId = Number(session?.user?.id);
if (!Number.isInteger(userId) || userId <= 0) return;
const realName = str(formData, "realName", NAME_MAX);
const availability = str(formData, "availability", TEXT_MAX);
const motivation = str(formData, "motivation", TEXT_MAX);
const experience = str(formData, "experience", TEXT_MAX);
const musicStyle = str(formData, "musicStyle", STYLE_MAX);
const ageRaw = Number(formData.get("age"));
const age = Number.isInteger(ageRaw) ? ageRaw : 0;
// Required fields per the schema (NOT NULL): real_name, age, availability,
// motivation. experience + music_style are nullable.
if (!realName || !availability || !motivation || age <= 0) return;
const now = new Date();
try {
await prisma.radioApplications.create({
data: {
userId: BigInt(userId),
realName,
age,
availability,
motivation,
experience: experience || null,
musicStyle: musicStyle || null,
status: "pending",
createdAt: now,
updatedAt: now,
},
});
} catch {
// DB unavailable or duplicate — fail soft; nothing to persist.
return;
}
revalidatePath("/radio/apply");
}
+44
View File
@@ -0,0 +1,44 @@
"use server";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
// radio_shouts.message is TEXT, but cap the write to keep shouts tweet-sized.
const MESSAGE_MAX = 255;
/**
* Post a radio shout.
*
* The AUTHOR (userId) is re-read from the session via auth() and is never
* trusted from the submitted FormData, so a crafted form cannot impersonate
* another account. radio_shouts.user_id is an UNSIGNED BIGINT, so the Int
* session id is widened to BigInt for the insert.
*/
export async function postShout(formData: FormData): Promise<void> {
const session = await auth();
const userId = Number(session?.user?.id);
if (!Number.isInteger(userId) || userId <= 0) return;
const message = String(formData.get("message") ?? "")
.trim()
.slice(0, MESSAGE_MAX);
if (!message) return;
const now = new Date();
try {
await prisma.radioShouts.create({
data: {
userId: BigInt(userId),
message,
createdAt: now,
updatedAt: now,
},
});
} catch {
// DB unavailable — fail soft; nothing to persist.
return;
}
revalidatePath("/radio/shouts");
}