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:
1 parent
e19debb795
commit
22d53d0e9c
40 files changed
+3781
-6
No files matched your search
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
/**
|
||||
* Client form for /shop/topup. Posts the chosen amount to /api/paypal/create,
|
||||
* then redirects the browser to PayPal's approval URL. After PayPal returns to
|
||||
* /shop/topup?token=<orderId>&status=success, it captures via /api/paypal/capture.
|
||||
*/
|
||||
export default function TopUpForm({
|
||||
currency,
|
||||
creditsPerUnit,
|
||||
}: {
|
||||
currency: string;
|
||||
creditsPerUnit: number;
|
||||
}) {
|
||||
const [amount, setAmount] = useState("5.00");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
const numeric = Number(amount);
|
||||
const credits = Number.isFinite(numeric) && numeric > 0 ? Math.floor(numeric * creditsPerUnit) : 0;
|
||||
|
||||
async function startCheckout(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setPending(true);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/create", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ amount: numeric }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
approveUrl?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (!res.ok || !data.approveUrl) {
|
||||
setError(data.error ?? "Could not start the PayPal checkout.");
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
// Hand off to PayPal for approval.
|
||||
window.location.href = data.approveUrl;
|
||||
} catch {
|
||||
setError("Network error — please try again.");
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function capture(orderId: string) {
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/paypal/capture", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ orderId }),
|
||||
});
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
ok?: boolean;
|
||||
credits?: number;
|
||||
error?: string;
|
||||
};
|
||||
if (res.ok && data.ok) {
|
||||
setSuccess(
|
||||
`Payment complete! ${(data.credits ?? 0).toLocaleString()} credits were added.`,
|
||||
);
|
||||
} else {
|
||||
setError(data.error ?? "We couldn't confirm your payment. Contact staff if charged.");
|
||||
}
|
||||
} catch {
|
||||
setError("Network error confirming payment — contact staff if you were charged.");
|
||||
} finally {
|
||||
setPending(false);
|
||||
// Clean the token/status query so a refresh doesn't re-capture.
|
||||
window.history.replaceState(null, "", "/shop/topup");
|
||||
}
|
||||
}
|
||||
|
||||
// On return from PayPal (?token=<orderId>&status=success), auto-capture once.
|
||||
if (typeof window !== "undefined" && !pending && !success) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const token = params.get("token");
|
||||
if (token && params.get("status") === "success") {
|
||||
// Defer to avoid setState during render.
|
||||
queueMicrotask(() => capture(token));
|
||||
}
|
||||
}
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-accent)" }}
|
||||
>
|
||||
{success}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={startCheckout}
|
||||
style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}
|
||||
>
|
||||
<label htmlFor="amount" style={{ fontWeight: 700 }}>
|
||||
Amount ({currency})
|
||||
</label>
|
||||
<input
|
||||
id="amount"
|
||||
name="amount"
|
||||
type="number"
|
||||
min={1}
|
||||
max={500}
|
||||
step={0.01}
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
aria-label={`Amount in ${currency}`}
|
||||
required
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
{["2.00", "5.00", "10.00", "25.00"].map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
className={`btn ${amount === v ? "btn-primary" : "btn-outline"}`}
|
||||
onClick={() => setAmount(v)}
|
||||
>
|
||||
{currency} {v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
You'll receive{" "}
|
||||
<strong>{credits.toLocaleString()}</strong> credits.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<button type="submit" className="btn btn-primary" disabled={pending || credits <= 0}>
|
||||
{pending ? "Redirecting…" : "Pay with PayPal"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
style={{ margin: 0, fontWeight: 700, color: "var(--color-danger)" }}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import TopUpForm from "./TopUpForm";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { creditsPerUnit, isPayPalConfigured, PAYPAL_CURRENCY } from "@/lib/services/paypal";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function TopUpPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ status?: string }>;
|
||||
}) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const sp = await searchParams;
|
||||
const id = Number(session.user.id);
|
||||
|
||||
// Current credits balance for context (fail soft).
|
||||
let user: { username: string; credits: number } | null = null;
|
||||
try {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: { username: true, credits: true },
|
||||
});
|
||||
} catch {
|
||||
user = null;
|
||||
}
|
||||
if (!user) redirect("/login");
|
||||
|
||||
const configured = isPayPalConfigured();
|
||||
const rate = creditsPerUnit();
|
||||
|
||||
return (
|
||||
<main>
|
||||
<div className="hero">
|
||||
<h1 style={{ marginBottom: "0.25rem" }}>Top up with PayPal</h1>
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
Pay securely with PayPal and your credits are added the moment the payment clears.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{sp.status === "cancel" ? (
|
||||
<div className="card" style={{ marginBottom: "1.5rem", borderColor: "var(--color-danger)" }}>
|
||||
<p style={{ margin: 0 }}>Checkout was cancelled — no payment was taken.</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid cols-2">
|
||||
<div className="card">
|
||||
<h3 style={{ marginTop: 0 }}>Choose an amount</h3>
|
||||
{configured ? (
|
||||
<TopUpForm currency={PAYPAL_CURRENCY} creditsPerUnit={rate} />
|
||||
) : (
|
||||
<p className="muted" style={{ margin: 0 }}>
|
||||
PayPal isn't configured yet. An administrator needs to set{" "}
|
||||
<code>PAYPAL_CLIENT_ID</code> and <code>PAYPAL_SECRET</code> (and optionally{" "}
|
||||
<code>PAYPAL_API</code> for sandbox vs. live).
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h3 style={{ marginTop: 0 }}>Your balance</h3>
|
||||
<p style={{ margin: "0 0 0.6rem" }}>
|
||||
Signed in as <strong>{user.username}</strong>.
|
||||
</p>
|
||||
<span className="currency">
|
||||
<span className="coin credits">cr</span>
|
||||
{user.credits.toLocaleString()}
|
||||
</span>
|
||||
<p className="muted" style={{ marginBottom: 0, marginTop: "0.85rem" }}>
|
||||
You receive <strong>{rate.toLocaleString()}</strong> credits per 1.00 {PAYPAL_CURRENCY}.
|
||||
Credits appear in-game the next time you log in.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user