Add public REST API, anti-abuse protections, radio/GitHub cron jobs

Phase A — Public REST API (was the biggest gap). 20 JSON endpoints under
/api mirroring AtomCMS: users/[username], online(+/count), me, articles
(+/[slug]), photos, home, staff, teams, leaderboard, shop(+/categories),
values(+/categories), settings, radio/{config,now-playing,listeners,
shouts}. Shared src/lib/api.ts (apiJson — BigInt-safe + CORS, pagination).
Read-only, fail-soft, and field-safe (never exposes password/auth_ticket/
2FA secrets/mail).

Phase B — Anti-abuse on registration: CAPTCHA (Cloudflare Turnstile /
Google reCAPTCHA, settings-driven, widget rendered on the register page),
VPN/proxy detection (proxycheck.io / IPQualityScore via /admin/vpn
settings), and max-accounts-per-IP. All fail-open when unconfigured.
src/lib/services/{captcha,ip-lookup}.ts.

Phase C — jobs-worker cron suite: radio-record-songs (30s, logs track
changes to radio_song_plays), radio-auto-dj (rotates radio_auto_dj_playlist
when no live DJ), github-update-check (hourly, sets update_available).
Shared src/lib/services/radio.ts (now-playing/listeners parsing).

Verified live (prod, amx_test): /api/* return real JSON (leaderboard 6
users, settings carry no secrets, user endpoint hides password). tsc 0,
vitest 49/49, next build 0 (20 new API routes).
This commit is contained in:
Simo committed 2026-06-28 21:44:02 +02:00
1 parent 5a4b6f27e9
commit 80f591a343
29 files changed
+1697 -7

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
/**
* JSON response helper for the public REST API. Serialises BigInt (Prisma ids)
* to strings — JSON.stringify throws on BigInt otherwise — and sets permissive
* CORS so the game client / external integrations can read it (mirrors the
* AtomCMS API CORS config).
*/
export function apiJson(data: unknown, init?: ResponseInit): NextResponse {
const body = JSON.stringify(data, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
return new NextResponse(body, {
status: init?.status ?? 200,
headers: {
"content-type": "application/json; charset=utf-8",
"access-control-allow-origin": "*",
"cache-control": "no-store",
...(init?.headers ?? {}),
},
});
}
/** Standard error envelope. */
export function apiError(message: string, status = 400): NextResponse {
return apiJson({ error: message }, { status });
}
/** Clamp a ?page / ?perPage pair from search params. */
export function pagination(searchParams: URLSearchParams, defaultPer = 20, maxPer = 100) {
const page = Math.max(1, Number(searchParams.get("page") ?? "1") || 1);
const perPage = Math.min(maxPer, Math.max(1, Number(searchParams.get("perPage") ?? defaultPer) || defaultPer));
return { page, perPage, skip: (page - 1) * perPage, take: perPage };
}
+76
View File
@@ -0,0 +1,76 @@
import { siteSettings } from "@/lib/services/site-settings";
/**
* Server-side CAPTCHA verification, driven by website_settings so staff pick the
* provider in housekeeping. Supports Cloudflare Turnstile and Google reCAPTCHA
* (the two AtomCMS offers, mutually exclusive). FAIL-OPEN by configuration: when
* no provider/secret is set, registration isn't blocked; only an explicitly
* configured provider with a failing/absent token blocks.
*
* Settings keys:
* captcha_provider = "turnstile" | "recaptcha" | "none" (default none)
* turnstile_secret / turnstile_site_key
* recaptcha_secret / recaptcha_site_key
*/
export interface CaptchaConfig {
provider: "turnstile" | "recaptcha" | "none";
siteKey: string;
/** Form field the widget writes the token into. */
field: string;
}
const TURNSTILE_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
const RECAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify";
/** Public config the register page needs to render the widget (no secrets). */
export async function captchaConfig(): Promise<CaptchaConfig> {
const provider = ((await siteSettings.get("captcha_provider", "none")) ?? "none").toLowerCase();
if (provider === "turnstile") {
return {
provider: "turnstile",
siteKey: (await siteSettings.get("turnstile_site_key", "")) ?? "",
field: "cf-turnstile-response",
};
}
if (provider === "recaptcha") {
return {
provider: "recaptcha",
siteKey: (await siteSettings.get("recaptcha_site_key", "")) ?? "",
field: "g-recaptcha-response",
};
}
return { provider: "none", siteKey: "", field: "" };
}
/** Verify a submitted token. Returns true when allowed (incl. fail-open). */
export async function verifyCaptcha(token: string | null, remoteIp?: string): Promise<boolean> {
const cfg = await captchaConfig();
if (cfg.provider === "none" || !cfg.siteKey) return true;
const secretKey = cfg.provider === "turnstile" ? "turnstile_secret" : "recaptcha_secret";
const secret = (await siteSettings.get(secretKey, "")) ?? "";
if (!secret) return true; // configured but no secret — don't hard-block
if (!token) return false;
const url = cfg.provider === "turnstile" ? TURNSTILE_URL : RECAPTCHA_URL;
const body = new URLSearchParams({ secret, response: token });
if (remoteIp) body.set("remoteip", remoteIp);
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body,
signal: controller.signal,
cache: "no-store",
});
clearTimeout(timer);
const data = (await res.json()) as { success?: boolean };
return data?.success === true;
} catch {
// Network/timeout — fail-open so a provider outage can't lock out signups.
return true;
}
}
+54
View File
@@ -0,0 +1,54 @@
import { siteSettings } from "@/lib/services/site-settings";
/**
* VPN / proxy / Tor detection via an external provider, driven by
* website_settings (configured at /admin/vpn). Mirrors AtomCMS's IP lookup used
* to block registrations from anonymising IPs. FAIL-OPEN: any error, missing
* config, or disabled toggle returns "not blocked".
*
* Settings keys: vpn_block_enabled ("1"), vpn_provider ("proxycheck" |
* "ipqualityscore"), vpn_api_key.
*/
export interface IpVerdict {
blocked: boolean;
reason?: string;
}
const PRIVATE_RE =
/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1|fc|fd|localhost$|0\.0\.0\.0$)/i;
export async function checkVpn(ip: string): Promise<IpVerdict> {
if (!ip || PRIVATE_RE.test(ip)) return { blocked: false };
if (!(await siteSettings.getBool("vpn_block_enabled", false))) return { blocked: false };
const provider = ((await siteSettings.get("vpn_provider", "proxycheck")) ?? "proxycheck").toLowerCase();
const apiKey = (await siteSettings.get("vpn_api_key", "")) ?? "";
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 4000);
if (provider === "ipqualityscore") {
if (!apiKey) return { blocked: false };
const res = await fetch(
`https://ipqualityscore.com/api/json/ip/${encodeURIComponent(apiKey)}/${encodeURIComponent(ip)}`,
{ signal: controller.signal, cache: "no-store" },
);
clearTimeout(timer);
const d = (await res.json()) as { proxy?: boolean; vpn?: boolean; tor?: boolean };
if (d?.vpn || d?.tor || d?.proxy) return { blocked: true, reason: "VPN/proxy detected" };
return { blocked: false };
}
// Default: proxycheck.io (works keyless at a low rate; key raises limits).
const url = `https://proxycheck.io/v2/${encodeURIComponent(ip)}?vpn=1&risk=1${apiKey ? `&key=${encodeURIComponent(apiKey)}` : ""}`;
const res = await fetch(url, { signal: controller.signal, cache: "no-store" });
clearTimeout(timer);
const d = (await res.json()) as Record<string, { proxy?: string; type?: string }>;
const entry = d?.[ip];
if (entry?.proxy === "yes") return { blocked: true, reason: `${entry.type ?? "Proxy"} detected` };
return { blocked: false };
} catch {
return { blocked: false };
}
}
+79
View File
@@ -0,0 +1,79 @@
import { siteSettings } from "@/lib/services/site-settings";
/**
* Best-effort radio stream helpers, shared by the public API and the jobs
* worker. They poll the now-playing / listeners endpoints configured in
* website_settings (AzureCast / Icecast / Shoutcast all differ), parsing the
* common shapes. Everything fails soft (returns null) on error/missing config.
*/
export interface NowPlaying {
title: string;
artist: string | null;
}
async function fetchJson(url: string, ms = 4000): Promise<unknown> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { signal: controller.signal, cache: "no-store" });
const text = await res.text();
try {
return JSON.parse(text);
} catch {
return text; // plain-text "Artist - Title" (Shoutcast/Icecast metadata)
}
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
function parseNowPlaying(d: unknown): NowPlaying | null {
if (!d) return null;
// AzureCast: { now_playing: { song: { title, artist } } }
const azure = (d as { now_playing?: { song?: { title?: string; artist?: string; text?: string } } })
.now_playing?.song;
if (azure?.title || azure?.text) {
return { title: azure.title ?? azure.text ?? "", artist: azure.artist ?? null };
}
// Generic JSON: { title, artist } or { songtitle }
const generic = d as { title?: string; artist?: string; songtitle?: string };
if (generic.title) return { title: generic.title, artist: generic.artist ?? null };
if (generic.songtitle) {
const [a, t] = generic.songtitle.split(" - ");
return t ? { title: t.trim(), artist: a.trim() } : { title: generic.songtitle, artist: null };
}
// Plain text "Artist - Title"
if (typeof d === "string" && d.trim()) {
const parts = d.split(" - ");
return parts.length > 1
? { title: parts.slice(1).join(" - ").trim(), artist: parts[0].trim() }
: { title: d.trim(), artist: null };
}
return null;
}
export async function fetchNowPlaying(): Promise<NowPlaying | null> {
const url = (await siteSettings.get("radio_now_playing_api_url", "")) ?? "";
if (!url) return null;
return parseNowPlaying(await fetchJson(url));
}
export async function fetchListeners(): Promise<number | null> {
const url = (await siteSettings.get("radio_listeners_api_url", "")) ?? "";
if (!url) return null;
const d = await fetchJson(url);
if (d == null) return null;
const obj = d as { listeners?: unknown; current_listeners?: unknown };
const raw =
typeof d === "number"
? d
: (obj.listeners ?? obj.current_listeners ?? (typeof d === "string" ? Number(d) : null));
const n = Number(
typeof raw === "object" && raw && "total" in (raw as Record<string, unknown>)
? (raw as { total: unknown }).total
: raw,
);
return Number.isFinite(n) ? n : null;
}