+
Broadcast email
+
Send a message to all users or just admins. Requires super-admin
access.
-
-
-
-
-
-
-
-
-
- setSubject(e.target.value)}
- />
+
+
+
+
+
+
+
+
+
+
+ setSubject(e.target.value)}
+ />
+
-
+
-
+
+
+ This will send an email to{" "}
+
+ {audience === "admins" ? "all admins" : "all users"}
+
+ .
+
-
-
+
+
);
};
@@ -256,101 +271,120 @@ const EmailLogsTab = () => {
}, [fetchLogs]);
return (
-
-
- Email send history
-
+
+
+
Email send history
+
Audit trail of test emails and broadcasts sent from the admin panel.
-
-
-
- {(loading || !data) && (
-
- Loading…
-
- )}
- {!loading && data && data.logs.length === 0 && (
-
- No email activity yet.
-
- )}
- {!loading && data && data.logs.length > 0 && (
-
- {data.logs.map((log) => {
- const meta = log.metadata ?? {};
- return (
-
-
-
-
- {log.action === "admin.email.broadcast_sent"
- ? "broadcast"
- : "test"}
+
+
+ {(loading || !data) && (
+
+ Loading…
+
+ )}
+ {!loading && data && data.logs.length === 0 && (
+
+ No email activity yet.
+
+ )}
+ {!loading && data && data.logs.length > 0 && (
+
+ {data.logs.map((log) => {
+ const meta = log.metadata ?? {};
+ const isBroadcast = log.action === "admin.email.broadcast_sent";
+ return (
+
+
+
+ {isBroadcast ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ {isBroadcast ? "broadcast" : "test"}
-
+
{String(meta.subject ?? "—")}
-
+
by {log.actorEmail ?? "unknown"}
- {log.action === "admin.email.broadcast_sent" &&
- meta.sent !== undefined && (
-
- {String(meta.sent)}/{String(meta.recipientCount)}{" "}
- sent
- {meta.audience ? ` · ${String(meta.audience)}` : ""}
-
- )}
- {log.action === "admin.email.test_sent" &&
- Boolean(meta.to) && (
- → {String(meta.to)}
- )}
-
+ {isBroadcast && meta.sent !== undefined && (
+
+ · {String(meta.sent)}/{String(meta.recipientCount)}{" "}
+ delivered
+ {meta.audience ? ` · ${String(meta.audience)}` : ""}
+
+ )}
+ {!isBroadcast && Boolean(meta.to) && (
+
· to {String(meta.to)}
+ )}
+
-
- {new Date(log.createdAt).toLocaleString()}
-
- );
- })}
-
- )}
- {data && data.totalPages > 1 && (
-
-
- {(data.page - 1) * data.pageSize + 1}–
- {Math.min(data.page * data.pageSize, data.total)} of {data.total}
+
+
+ );
+ })}
+
+ )}
+ {data && data.totalPages > 1 && (
+
+
+ {(data.page - 1) * data.pageSize + 1}–
+ {Math.min(data.page * data.pageSize, data.total)} of {data.total}
+
+
+
+
+ {page} / {data.totalPages}
-
-
-
- {page} / {data.totalPages}
-
-
-
+
- )}
-
-
+
+ )}
+
);
};
@@ -360,18 +394,18 @@ const EmailLogsTab = () => {
export const EmailPanel = () => (
-
-
-
+
+
+
Test send
-
-
+
+
Broadcast
-
-
- Logs
+
+
+ History
diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx
index 55c3f30..9044d71 100644
--- a/app/admin/layout.tsx
+++ b/app/admin/layout.tsx
@@ -4,14 +4,15 @@ import { SidebarProvider } from "@/components/ui/sidebar";
import { requireAdmin } from "@/lib/session";
import { AdminContainer } from "./components/admin-container";
-import { AdminSidebar } from "./components/admin-sidebar";
+import { AdminSidebarEnhanced } from "./components/admin-sidebar-enhanced";
+import { ADMIN_NAV_ITEMS } from "./config/nav";
const AdminLayout = async ({ children }: { children: ReactNode }) => {
const user = await requireAdmin();
return (
-
-
+ {
role: (user as { role?: string }).role ?? "user",
superAdmin: (user as { superAdmin?: boolean }).superAdmin ?? false,
}}
+ navItems={[...ADMIN_NAV_ITEMS]}
/>
{children}
diff --git a/app/admin/page.tsx b/app/admin/page.tsx
index 584c959..c0d8efe 100644
--- a/app/admin/page.tsx
+++ b/app/admin/page.tsx
@@ -1,56 +1,96 @@
-import { DollarSign, Server, TrendingUp, Users } from "lucide-react";
+import {
+ CreditCardIcon,
+ DollarSignIcon,
+ ServerIcon,
+ UsersIcon,
+ ZapIcon,
+} from "lucide-react";
+import Image from "next/image";
+import Link from "next/link";
+import { Avatar, AvatarFallback } from "@/components/ui/avatar";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { games } from "@/games";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/session";
+import { cn } from "@/lib/utils";
import { PageBody, PageHeader } from "../dashboard/components/page-header";
+import { SimpleBarChart } from "./components/charts";
+import { MetricsGrid } from "./components/metric-card";
-const StatCard = ({
- title,
- value,
- icon: Icon,
- description,
-}: {
- title: string;
- value: string | number;
- icon: React.ElementType;
- description?: string;
-}) => (
-
-
-
{value}
- {description && (
-
{description}
- )}
-
-);
+const getHealthClass = (pct: number) => {
+ if (pct >= 80) {
+ return "text-emerald-600 dark:text-emerald-400";
+ }
+ if (pct >= 50) {
+ return "text-amber-600 dark:text-amber-400";
+ }
+ return "text-red-600 dark:text-red-400";
+};
const AdminOverviewPage = async () => {
await requireAdmin();
const [
totalUsers,
+ newUsersThisMonth,
+ newUsersLastMonth,
totalServers,
activeServers,
+ failedServers,
activeSubscriptions,
monthlyRevenueCents,
+ lastMonthRevenueCents,
recentUsers,
+ recentServers,
+ serversByGame,
] = await Promise.all([
+ // User stats
prisma.user.count(),
+ prisma.user.count({
+ where: {
+ createdAt: {
+ gte: new Date(new Date().setDate(1)),
+ },
+ },
+ }),
+ prisma.user.count({
+ where: {
+ createdAt: {
+ gte: new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1),
+ lt: new Date(new Date().setDate(1)),
+ },
+ },
+ }),
+ // Server stats
prisma.server.count({ where: { deletedAt: null } }),
prisma.server.count({
where: { deletedAt: null, observedState: "running" },
}),
+ prisma.server.count({
+ where: {
+ deletedAt: null,
+ observedState: { in: ["failed", "unhealthy"] },
+ },
+ }),
+ // Subscription stats
prisma.subscription.count({ where: { status: "active" } }),
prisma.subscription.aggregate({
_sum: { pricePerMonthCents: true },
where: { status: "active" },
}),
+ prisma.subscription.aggregate({
+ _sum: { pricePerMonthCents: true },
+ where: {
+ createdAt: {
+ lt: new Date(new Date().setDate(1)),
+ },
+ status: "active",
+ },
+ }),
+ // Recent data
prisma.user.findMany({
orderBy: { createdAt: "desc" },
select: {
@@ -60,74 +100,370 @@ const AdminOverviewPage = async () => {
name: true,
role: true,
},
- take: 10,
+ take: 5,
+ }),
+ prisma.server.findMany({
+ orderBy: { createdAt: "desc" },
+ select: {
+ createdAt: true,
+ game: true,
+ id: true,
+ name: true,
+ observedState: true,
+ user: {
+ select: {
+ email: true,
+ name: true,
+ },
+ },
+ userId: true,
+ },
+ take: 5,
+ }),
+ // Servers by game
+ prisma.server.groupBy({
+ _count: true,
+ by: ["game"],
+ orderBy: { _count: { game: "desc" } },
+ where: { deletedAt: null },
}),
]);
const revenue = (
(monthlyRevenueCents._sum.pricePerMonthCents ?? 0) / 100
).toFixed(2);
+ const lastMonthRevenue = (
+ (lastMonthRevenueCents._sum.pricePerMonthCents ?? 0) / 100
+ ).toFixed(2);
+ const userChange =
+ newUsersLastMonth > 0
+ ? ((newUsersThisMonth - newUsersLastMonth) / newUsersLastMonth) * 100
+ : 0;
+ const revenueChange =
+ Number.parseFloat(lastMonthRevenue) > 0
+ ? ((Number.parseFloat(revenue) - Number.parseFloat(lastMonthRevenue)) /
+ Number.parseFloat(lastMonthRevenue)) *
+ 100
+ : 0;
+
+ const stoppedServers = totalServers - activeServers - failedServers;
+ const healthPct =
+ totalServers > 0 ? Math.round((activeServers / totalServers) * 100) : 0;
+
+ const gameData = serversByGame.slice(0, 6).map((g) => ({
+ label: g.game.charAt(0).toUpperCase() + g.game.slice(1),
+ value: g._count,
+ }));
+
+ const SERVER_STATE_CONFIG: Record<
+ string,
+ { dot: string; text: string; label: string }
+ > = {
+ failed: {
+ dot: "bg-red-500",
+ label: "Failed",
+ text: "text-red-600 dark:text-red-400",
+ },
+ running: {
+ dot: "bg-emerald-500",
+ label: "Running",
+ text: "text-emerald-600 dark:text-emerald-400",
+ },
+ stopped: {
+ dot: "bg-zinc-400",
+ label: "Stopped",
+ text: "text-zinc-500 dark:text-zinc-400",
+ },
+ unhealthy: {
+ dot: "bg-amber-500",
+ label: "Unhealthy",
+ text: "text-amber-600 dark:text-amber-400",
+ },
+ };
return (
<>
-
-
-
-
-
-
-
+
+ {/* Stat cards */}
+
0
+ ? {
+ isPositive: userChange >= 0,
+ period: "vs last month",
+ value: Math.round(Math.abs(userChange)),
+ }
+ : undefined,
+ description: `${newUsersThisMonth} joined this month`,
+ icon: ,
+ title: "Total users",
+ value: totalUsers.toLocaleString(),
+ },
+ {
+ accent: "emerald",
+ description: `${totalServers} total · ${failedServers} failed`,
+ icon: ,
+ title: "Active servers",
+ value: activeServers,
+ },
+ {
+ accent: "violet",
+ description: "active plans",
+ icon: ,
+ title: "Subscriptions",
+ value: activeSubscriptions.toLocaleString(),
+ },
+ {
+ accent: "amber",
+ change:
+ Number.parseFloat(lastMonthRevenue) > 0
+ ? {
+ isPositive: revenueChange >= 0,
+ period: "vs last month",
+ value: Math.round(Math.abs(revenueChange)),
+ }
+ : undefined,
+ icon: ,
+ title: "Monthly revenue",
+ value: `£${revenue}`,
+ },
+ ]}
+ />
-
-
-
Recent signups
-
-
- {recentUsers.map((u) => (
-
+ {/* Platform health */}
+
+
+
+
Platform health
+
+ Server state breakdown
+
+
+
-
-
- {u.name ?? u.email}
-
- {u.name && (
+ {healthPct}%
+
+
+
+ {/* Segmented bar */}
+ {totalServers > 0 && (
+
+ )}
+
+
+ {[
+ {
+ dot: "bg-emerald-500",
+ label: "Running",
+ text: "text-emerald-600 dark:text-emerald-400",
+ value: activeServers,
+ },
+ {
+ dot: "bg-zinc-400",
+ label: "Stopped",
+ text: "text-zinc-500",
+ value: stoppedServers,
+ },
+ {
+ dot: "bg-amber-500",
+ label: "Failed",
+ text: "text-amber-600 dark:text-amber-400",
+ value: failedServers,
+ },
+ ].map((s) => (
+
+
+
- {u.email}
+ {s.label}
- )}
-
-
-
- {u.role}
-
-
- {u.createdAt.toLocaleDateString()}
+
+
+ {s.value}
+ ))}
+
+
+
+
+
+
+
+ {/* Games chart */}
+ {gameData.length > 0 && (
+
+ )}
+
+
+ {/* Recent activity */}
+
+ {/* Recent signups */}
+
+
+
+
Recent signups
+
+ Latest user registrations
+
+
+
+
+ {recentUsers.length === 0 ? (
+
+ No recent signups
+
+ ) : (
+
+ {recentUsers.map((user) => (
+
+
+
+ {(user.name ?? user.email).charAt(0).toUpperCase()}
+
+
+
+
+ {user.name ?? user.email}
+
+ {user.name && (
+
+ {user.email}
+
+ )}
+
+
+ {user.role !== "user" && (
+
+ {user.role}
+
+ )}
+
+ {new Date(user.createdAt).toLocaleDateString()}
+
+
+
+ ))}
+
+ )}
+
+
+ {/* Recent servers */}
+
+
+
+
Recent servers
+
+ Latest server creations
+
+
+
+
+ {recentServers.length === 0 ? (
+
+ No recent servers
+
+ ) : (
+
+ {recentServers.map((server) => {
+ const game = games.find((g) => g.id === server.game);
+ const stateConf =
+ SERVER_STATE_CONFIG[server.observedState] ??
+ SERVER_STATE_CONFIG.stopped;
+ return (
+
+ {game ? (
+
+ ) : (
+
+
+
+ )}
+
+
+ {server.name}
+
+
+ {server.user?.name ?? server.user?.email}
+
+
+
+
+
+ {stateConf.label}
+
+
+
+ );
+ })}
- ))}
+ )}
diff --git a/app/admin/servers/actions/delete.ts b/app/admin/servers/actions/delete.ts
new file mode 100644
index 0000000..3cfc6d4
--- /dev/null
+++ b/app/admin/servers/actions/delete.ts
@@ -0,0 +1,81 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { z } from "zod";
+
+import { prisma } from "@/lib/db";
+import { getProviderForUser } from "@/lib/providers";
+import { requireAdmin } from "@/lib/session";
+
+const inputSchema = z.object({ serverId: z.string().min(1) });
+
+export type AdminDeleteServerInput = z.infer
;
+
+export type AdminDeleteServerResult =
+ | { ok: true }
+ | { error: string; ok: false };
+
+/**
+ * Admin delete server action
+ * Immediately deletes server from provider (bypassing workflow)
+ * Used by admins to force-delete problematic servers
+ */
+export const adminDeleteServer = async (
+ input: AdminDeleteServerInput
+): Promise => {
+ await requireAdmin();
+
+ const parsed = inputSchema.safeParse(input);
+ if (!parsed.success) {
+ return { error: "Invalid input", ok: false };
+ }
+
+ const server = await prisma.server.findFirst({
+ include: { user: { select: { id: true } } },
+ where: { id: parsed.data.serverId },
+ });
+
+ if (!server) {
+ return { error: "Not found", ok: false };
+ }
+
+ try {
+ // Delete from provider if server exists there
+ if (server.providerServerId) {
+ const provider = await getProviderForUser(server.user.id);
+ try {
+ await provider.deleteServer(server.providerServerId);
+ } catch (error) {
+ // Log but don't fail - server might already be gone
+ console.error(
+ `[admin-delete] Provider delete failed for ${server.id}:`,
+ error
+ );
+ }
+ }
+
+ // Mark as deleted in database
+ await prisma.server.update({
+ data: {
+ deletedAt: new Date(),
+ desiredState: "deleted",
+ },
+ where: { id: parsed.data.serverId },
+ });
+
+ // Clean up any associated records
+ await prisma.serverMember.deleteMany({
+ where: { serverId: parsed.data.serverId },
+ });
+
+ revalidatePath("/admin/servers");
+ return { ok: true };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Unknown error";
+ console.error(
+ `[admin-delete] Failed to delete server ${server.id}:`,
+ error
+ );
+ return { error: message, ok: false };
+ }
+};
diff --git a/app/admin/servers/servers-table.tsx b/app/admin/servers/servers-table.tsx
index 8b2a414..1984551 100644
--- a/app/admin/servers/servers-table.tsx
+++ b/app/admin/servers/servers-table.tsx
@@ -6,13 +6,23 @@ import {
ExternalLink,
Search,
Server,
+ Trash2,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
-import { Badge } from "@/components/ui/badge";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
@@ -22,7 +32,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { Skeleton } from "@/components/ui/skeleton";
import { games } from "@/games";
+import { cn } from "@/lib/utils";
+
+import { adminDeleteServer } from "./actions/delete";
interface AdminServer {
id: string;
@@ -45,23 +59,33 @@ interface PagedResponse {
totalPages: number;
}
-const stateBadgeVariant = (
- state: string,
- desiredState: string
-): "default" | "secondary" | "destructive" | "outline" => {
+const stateBadgeClass = (state: string, desiredState: string): string => {
if (desiredState === "deleted") {
- return "destructive";
+ return "border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400";
}
if (state === "running") {
- return "default";
+ return "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400";
}
if (state === "failed" || state === "lost") {
- return "destructive";
+ return "border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400";
+ }
+ if (state === "unhealthy") {
+ return "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400";
+ }
+ return "border-zinc-500/40 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400";
+};
+
+const getServerStateColor = (state: string) => {
+ if (state === "running") {
+ return "bg-emerald-500";
}
if (state === "unhealthy") {
- return "secondary";
+ return "bg-amber-500";
+ }
+ if (["failed", "lost", "deleting"].includes(state)) {
+ return "bg-red-500";
}
- return "outline";
+ return "bg-zinc-400";
};
const STATES = [
@@ -80,6 +104,8 @@ export const ServersTable = () => {
const [search, setSearch] = useState("");
const [status, setStatus] = useState("all");
const [loading, setLoading] = useState(false);
+ const [deletingIds, setDeletingIds] = useState>(new Set());
+ const [deleteTarget, setDeleteTarget] = useState(null);
const fetchServers = useCallback(async () => {
setLoading(true);
@@ -103,6 +129,31 @@ export const ServersTable = () => {
}
}, [page, search, status]);
+ const handleDeleteServer = useCallback(
+ async (serverId: string) => {
+ setDeletingIds((prev) => new Set([...prev, serverId]));
+ setDeleteTarget(null);
+ try {
+ const result = await adminDeleteServer({ serverId });
+ if (result.ok) {
+ toast.success("Server deleted");
+ void fetchServers();
+ } else {
+ toast.error(result.error || "Failed to delete server");
+ }
+ } catch {
+ toast.error("Failed to delete server");
+ } finally {
+ setDeletingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(serverId);
+ return next;
+ });
+ }
+ },
+ [fetchServers]
+ );
+
useEffect(() => {
void fetchServers();
}, [fetchServers]);
@@ -112,7 +163,7 @@ export const ServersTable = () => {
{/* Filters */}
-
+
{
setPage(1);
}}
>
-
+
@@ -145,6 +196,7 @@ export const ServersTable = () => {
{/* Table */}
-
+
{(loading || !data) && (
-
- Loading…
+
+ {Array.from({ length: 5 }).map((_, i) => (
+
+ ))}
)}
- {!loading && data && data.servers.length === 0 && (
-
+ {!loading && data?.servers.length === 0 && (
+
No servers found.
)}
@@ -172,67 +234,97 @@ export const ServersTable = () => {
{data.servers.map((server) => {
const game = games.find((g) => g.id === server.game);
const deleting = server.desiredState === "deleted";
+ const stateKey = deleting ? "deleting" : server.observedState;
return (
-
- {game ? (
-
- ) : (
-
-
-
- )}
-
-
-
- {server.name}
-
-
+ ) : (
+
+
+
+ )}
+
+ {/* Name + owner */}
+
+
+
+ {server.name}
+
+
+
+
c.startsWith("text-"))
+ .join(" ") || "text-muted-foreground"
)}
- className="shrink-0 text-xs"
>
- {deleting ? "deleting" : server.observedState}
-
+ {stateKey}
+
-
- {server.user.name ?? server.user.email}
- {server.ipv4 && (
- {server.ipv4}
- )}
-
+
+ {server.user.name ?? server.user.email}
+ {server.ipv4 && (
+ {server.ipv4}
+ )}
+
-
-
- {server.location}
-
-
+ {/* Meta — hidden on mobile */}
+
+ {server.location}
+
{new Date(server.createdAt).toLocaleDateString()}
-
+
+ {/* Open in dashboard */}
+
+
+ {/* Delete */}
+
);
})}
@@ -242,7 +334,7 @@ export const ServersTable = () => {
{/* Pagination */}
{data && data.totalPages > 1 && (
-
+
{(data.page - 1) * data.pageSize + 1}–
{Math.min(data.page * data.pageSize, data.total)} of {data.total}
@@ -251,7 +343,8 @@ export const ServersTable = () => {
)}
+
+
!o && setDeleteTarget(null)}
+ >
+
+
+ Delete this server?
+
+ This will remove the server from the provider immediately. This
+ action cannot be undone.
+
+
+
+ Cancel
+ {
+ if (deleteTarget) {
+ handleDeleteServer(deleteTarget);
+ }
+ }}
+ >
+ Delete
+
+
+
+
);
};
diff --git a/app/admin/sessions/sessions-table.tsx b/app/admin/sessions/sessions-table.tsx
index 657ec31..5e98af7 100644
--- a/app/admin/sessions/sessions-table.tsx
+++ b/app/admin/sessions/sessions-table.tsx
@@ -1,18 +1,20 @@
"use client";
import {
+ AppleIcon,
ChevronLeft,
ChevronRight,
- Monitor,
- RefreshCw,
- Trash2,
+ GlobeIcon,
+ LaptopIcon,
+ RefreshCwIcon,
+ SmartphoneIcon,
+ Trash2Icon,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
-import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Card, CardContent } from "@/components/ui/card";
+import { cn } from "@/lib/utils";
interface AdminSession {
id: string;
@@ -33,23 +35,73 @@ interface PagedResponse {
totalPages: number;
}
-const parseUa = (ua: string | null) => {
+const getDeviceInfo = (
+ ua: string | null
+): { label: string; icon: React.ElementType; os: string } => {
if (!ua) {
- return "Unknown device";
+ return { icon: GlobeIcon, label: "Unknown", os: "Unknown" };
}
- if (/iPhone|iPad|Android/iu.test(ua)) {
- return "Mobile";
+ if (/iPhone/iu.test(ua)) {
+ return { icon: SmartphoneIcon, label: "iPhone", os: "iOS" };
+ }
+ if (/iPad/iu.test(ua)) {
+ return { icon: AppleIcon, label: "iPad", os: "iPadOS" };
+ }
+ if (/Android/iu.test(ua)) {
+ return { icon: SmartphoneIcon, label: "Android", os: "Android" };
}
if (/Mac/iu.test(ua)) {
- return "macOS";
+ return { icon: LaptopIcon, label: "Mac", os: "macOS" };
}
if (/Windows/iu.test(ua)) {
- return "Windows";
+ return { icon: LaptopIcon, label: "Windows PC", os: "Windows" };
}
if (/Linux/iu.test(ua)) {
- return "Linux";
+ return { icon: LaptopIcon, label: "Linux", os: "Linux" };
+ }
+ return { icon: GlobeIcon, label: "Browser", os: "Unknown" };
+};
+
+const getBrowserName = (ua: string | null): string => {
+ if (!ua) {
+ return "";
+ }
+ if (/Edg\//iu.test(ua)) {
+ return "Edge";
+ }
+ if (/OPR\//iu.test(ua) || /Opera/iu.test(ua)) {
+ return "Opera";
+ }
+ if (/Firefox/iu.test(ua)) {
+ return "Firefox";
+ }
+ if (/Chrome/iu.test(ua)) {
+ return "Chrome";
}
- return "Browser";
+ if (/Safari/iu.test(ua)) {
+ return "Safari";
+ }
+ return "";
+};
+
+const getExpiryClass = (expired: boolean, expiresInDays: number) => {
+ if (expired) {
+ return "text-destructive";
+ }
+ if (expiresInDays <= 1) {
+ return "text-amber-600 dark:text-amber-400";
+ }
+ return "text-emerald-600 dark:text-emerald-400";
+};
+
+const getExpiryLabel = (expired: boolean, expiresInDays: number) => {
+ if (expired) {
+ return "expired";
+ }
+ if (expiresInDays > 0) {
+ return `expires in ${expiresInDays}d`;
+ }
+ return "expires today";
};
export const SessionsTable = () => {
@@ -107,88 +159,114 @@ export const SessionsTable = () => {
return (
-
+
+ {data && (
+
+ {data.total} active session{data.total === 1 ? "" : "s"}
+
+ )}
fetchSessions()}
+ onClick={() => void fetchSessions()}
>
-
+
Refresh
-
-
- {(loading || !data) && (
-
- Loading…
-
- )}
- {!loading && data && data.sessions.length === 0 && (
-
- No active sessions.
-
- )}
- {!loading && data && data.sessions.length > 0 && (
-
- {data.sessions.map((session) => {
- const expiresIn =
- new Date(session.expiresAt).getTime() - Date.now();
- const expiresInDays = Math.round(expiresIn / 86_400_000);
- return (
-
-
-
-
-
-
-
+
+ {(loading || !data) && (
+
+ Loading…
+
+ )}
+ {!loading && data && data.sessions.length === 0 && (
+
+ No active sessions.
+
+ )}
+ {!loading && data && data.sessions.length > 0 && (
+
+ {data.sessions.map((session) => {
+ const expiresIn =
+ new Date(session.expiresAt).getTime() - Date.now();
+ const expiresInDays = Math.round(expiresIn / 86_400_000);
+ const expired = expiresIn <= 0;
+ const device = getDeviceInfo(session.userAgent);
+ const browser = getBrowserName(session.userAgent);
+ const DeviceIcon = device.icon;
+ const createdDate = new Date(
+ session.createdAt
+ ).toLocaleDateString(undefined, {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ });
+
+ return (
+
+
+ {/* Device icon */}
+
+
+
+
+ {/* Info */}
+
+
+
{session.user.name ?? session.user.email}
- {session.user.name && (
-
- {session.user.email}
-
- )}
-
-
-
- {parseUa(session.userAgent)}
-
- {session.ipAddress && (
-
- {session.ipAddress}
-
- )}
-
- expires in{" "}
- {expiresInDays > 0 ? `${expiresInDays}d` : "< 1d"}
+
+ {session.user.name && (
+
+ {session.user.email}
-
+ )}
-
-
handleRevoke(session)}
- >
-
- {revoking === session.id ? "Revoking…" : "Revoke"}
-
+
+
+
+ {device.os}
+ {browser ? ` · ${browser}` : ""}
+
+ {session.ipAddress && (
+ {session.ipAddress}
+ )}
+ Started {createdDate}
+
+ {getExpiryLabel(expired, expiresInDays)}
+
+
+
- );
- })}
-
- )}
-
-
+
+
handleRevoke(session)}
+ >
+
+ {revoking === session.id ? "Revoking…" : "Revoke"}
+
+
+ );
+ })}
+
+ )}
+
{data && data.totalPages > 1 && (
@@ -198,10 +276,11 @@ export const SessionsTable = () => {
setPage((p) => p - 1)}
>
@@ -210,10 +289,11 @@ export const SessionsTable = () => {
{page} / {data.totalPages}
= data.totalPages}
size="icon"
variant="ghost"
- className="size-7"
- disabled={page >= data.totalPages}
onClick={() => setPage((p) => p + 1)}
>
diff --git a/app/admin/subscriptions/page.tsx b/app/admin/subscriptions/page.tsx
index 6ca728d..940e43e 100644
--- a/app/admin/subscriptions/page.tsx
+++ b/app/admin/subscriptions/page.tsx
@@ -1,39 +1,37 @@
-import { DollarSign, Receipt, TrendingUp } from "lucide-react";
+import { DollarSign, ExternalLink, Receipt, TrendingUp } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { prisma } from "@/lib/db";
import { requireSuperAdmin } from "@/lib/session";
+import { cn } from "@/lib/utils";
import { PageBody, PageHeader } from "../../dashboard/components/page-header";
+import { MetricCard } from "../components";
-const statusVariant = (
- status: string
-): "default" | "secondary" | "destructive" | "outline" => {
+const subStatusClass = (status: string): string => {
if (status === "active") {
- return "default";
+ return "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400";
}
if (status === "past_due" || status === "unpaid") {
- return "destructive";
+ return "border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400";
}
if (status === "canceled" || status === "incomplete_expired") {
- return "secondary";
+ return "border-zinc-500/40 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400";
}
- return "outline";
+ return "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400";
};
-const invoiceStatusVariant = (
- status: string
-): "default" | "secondary" | "destructive" | "outline" => {
+const invoiceStatusClass = (status: string): string => {
if (status === "paid") {
- return "default";
+ return "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400";
}
if (status === "open") {
- return "outline";
+ return "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400";
}
if (status === "void" || status === "uncollectible") {
- return "secondary";
+ return "border-zinc-500/40 bg-zinc-500/10 text-zinc-500 dark:text-zinc-400";
}
- return "destructive";
+ return "border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400";
};
const AdminSubscriptionsPage = async () => {
@@ -100,56 +98,31 @@ const AdminSubscriptionsPage = async () => {
{/* Summary */}
-
-
-
- Monthly revenue
-
-
-
-
-
-
- £{(activeRevenue / 100).toFixed(2)}
-
-
- from active subscriptions
-
-
+
}
+ accent="emerald"
+ />
-
-
-
- Active subs
-
-
-
-
-
-
{activeCount}
-
- {totalCount} total
-
-
+
}
+ accent="blue"
+ />
-
-
-
- {pastDueCount}
-
-
- require attention
-
-
+
}
+ accent={pastDueCount > 0 ? "red" : "zinc"}
+ />
-
+
Breakdown
@@ -160,8 +133,11 @@ const AdminSubscriptionsPage = async () => {
className="flex items-center justify-between"
>
{r.status.replace("_", " ")}
@@ -176,7 +152,7 @@ const AdminSubscriptionsPage = async () => {
{/* Subscriptions table */}
-
+
All subscriptions
@@ -204,8 +180,11 @@ const AdminSubscriptionsPage = async () => {
{sub.status.replace("_", " ")}
@@ -244,7 +223,7 @@ const AdminSubscriptionsPage = async () => {
{/* Recent invoices */}
-
+
Recent invoices
@@ -283,8 +262,11 @@ const AdminSubscriptionsPage = async () => {
{inv.status}
@@ -301,8 +283,9 @@ const AdminSubscriptionsPage = async () => {
href={inv.invoiceUrl}
target="_blank"
rel="noopener noreferrer"
- className="text-xs text-primary underline-offset-2 hover:underline"
+ className="inline-flex items-center gap-1 text-xs text-primary underline-offset-2 hover:underline"
>
+
View
)}
diff --git a/app/admin/users/users-table.tsx b/app/admin/users/users-table.tsx
index 6131b9a..2a01f84 100644
--- a/app/admin/users/users-table.tsx
+++ b/app/admin/users/users-table.tsx
@@ -18,7 +18,6 @@ import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Card, CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
@@ -36,7 +35,9 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
+import { cn } from "@/lib/utils";
interface AdminUser {
id: string;
@@ -69,7 +70,10 @@ const RoleBadge = ({
}) => {
if (superAdmin) {
return (
-
+
Super Admin
@@ -77,18 +81,31 @@ const RoleBadge = ({
}
if (role === "admin") {
return (
-
+
Admin
);
}
return (
-
+
User
);
};
+const getAvatarClass = (superAdmin: boolean, role: string) => {
+ if (superAdmin) {
+ return "bg-violet-500/15 text-violet-600 dark:text-violet-400";
+ }
+ if (role === "admin") {
+ return "bg-blue-500/15 text-blue-600 dark:text-blue-400";
+ }
+ return "bg-muted";
+};
+
export const UsersTable = () => {
const [data, setData] = useState(null);
const [page, setPage] = useState(1);
@@ -211,9 +228,9 @@ export const UsersTable = () => {
return (
{/* Search */}
-
-
-
+
{/* Table */}
-
-
- {(loading || !data) && (
-
- Loading…
-
- )}
- {!loading && data && data.users.length === 0 && (
-
- No users found.
-
- )}
- {!loading && data && data.users.length > 0 && (
-
- {data.users.map((user) => (
-
-
-
- {user.image && (
-
- )}
-
- {(user.name ?? user.email).charAt(0).toUpperCase()}
-
-
-
-
- {user.name ?? user.email}
-
- {user.name && (
-
- {user.email}
-
- )}
-
-
+
+ {(loading || !data) && (
+
+ {Array.from({ length: 5 }).map((_, i) => (
+
+ ))}
+
+ )}
+ {!loading && data?.users.length === 0 && (
+
+ No users found.
+
+ )}
+ {!loading && data && data.users.length > 0 && (
+
+ {data.users.map((user) => (
+
+ {/* Avatar */}
+
+ {user.image && (
+
+ )}
+
+ {(user.name ?? user.email).charAt(0).toUpperCase()}
+
+
-
+ {/* Name / email */}
+
+
+
+ {user.name ?? user.email}
+
+
{user.banned && (
-
+
Banned
)}
-
-
- {user._count.servers} server
- {user._count.servers === 1 ? "" : "s"}
-
-
- {new Date(user.createdAt).toLocaleDateString()}
+
+ {user.name && (
+
+ {user.email}
+ )}
+
-
-
-
-
-
-
-
-
- Role
-
- handleSetRole(user, "user")}
- >
-
- Set User
-
- handleSetRole(user, "admin")}
- >
-
- Set Admin
-
+ {/* Stats — hidden on mobile */}
+
+
+ {user._count.servers}{" "}
+ {user._count.servers === 1 ? "server" : "servers"}
+
+ {new Date(user.createdAt).toLocaleDateString()}
+
+
+ {/* Actions */}
+
+
+
+
+
+
+
+
+ Role
+
+ handleSetRole(user, "user")}
+ >
+
+ Set User
+
+ handleSetRole(user, "admin")}
+ >
+
+ Set Admin
+
+ handleToggleSuperAdmin(user)}
+ >
+ {user.superAdmin ? (
+ <>
+
+ Remove Super Admin
+ >
+ ) : (
+ <>
+
+ Make Super Admin
+ >
+ )}
+
+
+ {user.banned ? (
+ handleUnban(user)}>
+
+ Unban
+
+ ) : (
+ setBanTarget(user)}
+ >
+
+ Ban user
+
+ )}
+ {user.role === "user" && !user.superAdmin && (
+ <>
+
handleToggleSuperAdmin(user)}
+ onSelect={() => handleImpersonate(user)}
>
- {user.superAdmin ? (
- <>
-
- Remove Super Admin
- >
- ) : (
- <>
-
- Make Super Admin
- >
- )}
+
+ Impersonate
-
- {user.banned ? (
- handleUnban(user)}>
-
- Unban
-
- ) : (
- setBanTarget(user)}
- >
-
- Ban user
-
- )}
- {/* Impersonate — only for plain users, never admins */}
- {user.role === "user" && !user.superAdmin && (
- <>
-
- handleImpersonate(user)}
- >
-
- Impersonate
-
- >
- )}
-
-
-
-
- ))}
-
- )}
-
-
+ >
+ )}
+
+
+
+ ))}
+
+ )}
+
{/* Pagination */}
{data && data.totalPages > 1 && (
-
+
{(data.page - 1) * data.pageSize + 1}–
{Math.min(data.page * data.pageSize, data.total)} of {data.total}
@@ -385,7 +429,8 @@ export const UsersTable = () => {
setPage((p) => p - 1)}
>
@@ -397,7 +442,8 @@ export const UsersTable = () => {
= data.totalPages}
onClick={() => setPage((p) => p + 1)}
>
diff --git a/app/api/admin/analytics/route.ts b/app/api/admin/analytics/route.ts
new file mode 100644
index 0000000..6caebab
--- /dev/null
+++ b/app/api/admin/analytics/route.ts
@@ -0,0 +1,204 @@
+import type { NextRequest } from "next/server";
+import { NextResponse } from "next/server";
+
+import { prisma } from "@/lib/db";
+import { requireAdmin } from "@/lib/session";
+
+export const GET = async (request: NextRequest): Promise => {
+ try {
+ // Verify admin access
+ await requireAdmin();
+
+ const { searchParams } = request.nextUrl;
+ const range = Number.parseInt(searchParams.get("range") || "30", 10);
+
+ // Calculate date range
+ const endDate = new Date();
+ endDate.setHours(23, 59, 59, 999);
+
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - range);
+ startDate.setHours(0, 0, 0, 0);
+
+ // 1. Monthly Recurring Revenue (MRR) in GBP
+ const mrrResult = await prisma.subscription.aggregate({
+ _sum: { pricePerMonthCents: true },
+ where: { status: "active" },
+ });
+ const mrr = (mrrResult._sum.pricePerMonthCents ?? 0) / 100;
+
+ // 2. Active Servers (running state)
+ const activeServersCount = await prisma.server.count({
+ where: {
+ deletedAt: null,
+ observedState: "running",
+ },
+ });
+
+ // 3. Total Servers (not deleted)
+ const totalServersCount = await prisma.server.count({
+ where: { deletedAt: null },
+ });
+
+ // 4. Server Uptime %
+ const serverUptime =
+ totalServersCount > 0
+ ? (activeServersCount / totalServersCount) * 100
+ : 0;
+
+ // 5. New Users This Month
+ const firstDayOfMonth = new Date();
+ firstDayOfMonth.setDate(1);
+ firstDayOfMonth.setHours(0, 0, 0, 0);
+
+ const firstDayNextMonth = new Date(firstDayOfMonth);
+ firstDayNextMonth.setMonth(firstDayNextMonth.getMonth() + 1);
+
+ const newUsersThisMonth = await prisma.user.count({
+ where: {
+ createdAt: {
+ gte: firstDayOfMonth,
+ lt: firstDayNextMonth,
+ },
+ },
+ });
+
+ // 6. Revenue Trend - daily breakdown
+ const revenueTrendRaw = await prisma.subscription.findMany({
+ orderBy: { createdAt: "asc" },
+ select: {
+ createdAt: true,
+ pricePerMonthCents: true,
+ },
+ where: {
+ createdAt: { gte: startDate, lte: endDate },
+ status: "active",
+ },
+ });
+
+ // Group by date and sum revenues
+ const revenueTrendMap = new Map();
+
+ // Initialize all dates in range with 0
+ for (let i = 0; i <= range; i += 1) {
+ const d = new Date(startDate);
+ d.setDate(d.getDate() + i);
+ const [dateKey = ""] = d.toISOString().split("T");
+ if (!revenueTrendMap.has(dateKey)) {
+ revenueTrendMap.set(dateKey, 0);
+ }
+ }
+
+ // Add actual revenues
+ for (const { createdAt, pricePerMonthCents } of revenueTrendRaw) {
+ const [dateKey = ""] = createdAt.toISOString().split("T");
+ revenueTrendMap.set(
+ dateKey,
+ (revenueTrendMap.get(dateKey) ?? 0) + (pricePerMonthCents ?? 0) / 100
+ );
+ }
+
+ const revenueTrend = [...revenueTrendMap]
+ .toSorted((a, b) => a[0].localeCompare(b[0]))
+ .map(([date, revenue]) => ({
+ date,
+ revenue: Number.parseFloat(revenue.toFixed(2)),
+ }));
+
+ // 7. Server Count by Game
+ // Top 10 games
+ const serversByGameRaw = await prisma.server.groupBy({
+ _count: true,
+ by: ["game"],
+ orderBy: { _count: { id: "desc" } },
+ take: 10,
+ where: { deletedAt: null },
+ });
+
+ const serversByGame = serversByGameRaw.map((item) => ({
+ count: item._count,
+ game: item.game.charAt(0).toUpperCase() + item.game.slice(1),
+ }));
+
+ // 8. Server Status Breakdown
+ const serverStatusRaw = await prisma.server.groupBy({
+ _count: true,
+ by: ["observedState"],
+ where: { deletedAt: null },
+ });
+
+ const serverStatus = serverStatusRaw.map((item) => ({
+ count: item._count,
+ status:
+ item.observedState.charAt(0).toUpperCase() +
+ item.observedState.slice(1),
+ }));
+
+ // 9. New Signups Trend
+ const signupsTrendRaw = await prisma.user.findMany({
+ orderBy: { createdAt: "asc" },
+ select: { createdAt: true },
+ where: {
+ createdAt: { gte: startDate, lte: endDate },
+ },
+ });
+
+ const signupsTrendMap = new Map();
+
+ // Initialize all dates in range with 0
+ for (let i = 0; i <= range; i += 1) {
+ const d = new Date(startDate);
+ d.setDate(d.getDate() + i);
+ const [dateKey = ""] = d.toISOString().split("T");
+ if (!signupsTrendMap.has(dateKey)) {
+ signupsTrendMap.set(dateKey, 0);
+ }
+ }
+
+ // Add actual signups
+ for (const { createdAt } of signupsTrendRaw) {
+ const [dateKey = ""] = createdAt.toISOString().split("T");
+ signupsTrendMap.set(dateKey, (signupsTrendMap.get(dateKey) ?? 0) + 1);
+ }
+
+ const signupsTrend = [...signupsTrendMap]
+ .toSorted((a, b) => a[0].localeCompare(b[0]))
+ .map(([date, signups]) => ({
+ date,
+ signups,
+ }));
+
+ // 10. Subscription Status Distribution
+ const subscriptionStatusRaw = await prisma.subscription.groupBy({
+ _count: true,
+ by: ["status"],
+ orderBy: { _count: { id: "desc" } },
+ });
+
+ const subscriptionStatus = subscriptionStatusRaw.map((item) => ({
+ count: item._count,
+ status:
+ item.status.charAt(0).toUpperCase() +
+ item.status.slice(1).replaceAll("_", " ").toLowerCase(),
+ }));
+
+ return NextResponse.json({
+ activeServers: activeServersCount,
+ mrr,
+ newUsersThisMonth,
+ revenueTrend,
+ serverStatus,
+ serverUptime,
+ serversByGame,
+ signupsTrend,
+ subscriptionStatus,
+ totalServers: totalServersCount,
+ });
+ } catch (error) {
+ console.error("Analytics API error:", error);
+ return NextResponse.json(
+ { error: "Failed to fetch analytics" },
+ { status: 500 }
+ );
+ }
+};
diff --git a/app/api/agent/errors/route.ts b/app/api/agent/errors/route.ts
new file mode 100644
index 0000000..9b27af7
--- /dev/null
+++ b/app/api/agent/errors/route.ts
@@ -0,0 +1,109 @@
+/**
+ * Agent error reporting endpoint
+ * Agents call this during provisioning/baking to report errors
+ */
+
+import { randomUUID } from "node:crypto";
+
+import type { Prisma } from "@prisma/client";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { verifyAgentRequest } from "@/lib/agent/signing";
+import { prisma } from "@/lib/db";
+
+const errorReportSchema = z.object({
+ details: z.record(z.string(), z.unknown()).optional(),
+ errorCode: z.string().min(1),
+ errorMessage: z.string().min(1),
+ phase: z.enum([
+ "provisioning",
+ "baking",
+ "agent_bootstrap",
+ "install",
+ "unknown",
+ ]),
+ timestamp: z.number().optional(),
+});
+
+export const runtime = "nodejs";
+
+export const POST = async (request: Request) => {
+ try {
+ // Verify agent identity and integrity
+ const { verified, body } = await verifyAgentRequest(request);
+
+ // Parse the error report
+ const data = JSON.parse(body);
+ const parsed = errorReportSchema.safeParse(data);
+
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: "Invalid error report format" },
+ { status: 400 }
+ );
+ }
+
+ const { errorCode, errorMessage, phase, details, timestamp } = parsed.data;
+ const now = new Date();
+
+ // Find the server for this agent
+ const agent = await prisma.agent.findUnique({
+ include: { server: true },
+ where: { id: verified.agentId },
+ });
+
+ if (!agent) {
+ return NextResponse.json({ error: "Agent not found" }, { status: 404 });
+ }
+
+ // Create error record
+ await prisma.agentError.create({
+ data: {
+ agentId: verified.agentId,
+ details: (details ?? {}) as unknown as Prisma.InputJsonValue,
+ errorCode,
+ errorMessage,
+ id: randomUUID(),
+ phase,
+ recordedAt: now,
+ reportedAt: timestamp ? new Date(timestamp) : now,
+ serverId: agent.serverId,
+ },
+ });
+
+ // Update server phase to "errored" if not already marked as failed
+ if (agent.server.observedState !== "failed") {
+ await prisma.server.update({
+ data: {
+ observedState: "failed",
+ phase: "errored",
+ },
+ where: { id: agent.serverId },
+ });
+ }
+
+ // Log for debugging
+ console.log(
+ `[agent-error] Server ${agent.serverId} reported error in ${phase}:`,
+ {
+ details,
+ errorCode,
+ errorMessage,
+ }
+ );
+
+ return NextResponse.json({ success: true }, { status: 200 });
+ } catch (error) {
+ if (error instanceof Error && error.constructor.name === "AgentAuthError") {
+ const status = (error as { status?: number }).status ?? 401;
+ return NextResponse.json({ error: error.message }, { status });
+ }
+
+ console.error("[agent-error] Error processing report:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 }
+ );
+ }
+};
diff --git a/app/api/servers/[id]/backups/limit-check/route.ts b/app/api/servers/[id]/backups/limit-check/route.ts
new file mode 100644
index 0000000..4185792
--- /dev/null
+++ b/app/api/servers/[id]/backups/limit-check/route.ts
@@ -0,0 +1,80 @@
+import { prisma } from "@/lib/db";
+import { ADDON_DEFAULTS } from "@/lib/pricing";
+import { requireUser } from "@/lib/session";
+
+export const GET = async (
+ _request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) => {
+ const user = await requireUser();
+ const { id: serverId } = await params;
+
+ // Verify server ownership
+ const server = await prisma.server.findFirst({
+ select: { id: true },
+ where: { id: serverId, userId: user.id },
+ });
+
+ if (!server) {
+ return Response.json({ error: "Server not found" }, { status: 404 });
+ }
+
+ // Get subscription + addons
+ const subscription = await prisma.subscription.findUnique({
+ select: {
+ addons: {
+ where: { type: "backup" },
+ },
+ status: true,
+ },
+ where: { serverId },
+ });
+
+ if (!subscription) {
+ return Response.json(
+ { error: "No subscription for server" },
+ { status: 404 }
+ );
+ }
+
+ // Check if subscription is active (required to create backups)
+ const isActive =
+ subscription.status === "active" || subscription.status === "trialing";
+ if (!isActive) {
+ return Response.json(
+ {
+ allowed: false,
+ message: `Cannot create backups while subscription is ${subscription.status}`,
+ reason: "subscription_not_active",
+ },
+ { status: 402 }
+ );
+ }
+
+ // Get addon for backups
+ const [backupAddon] = subscription.addons;
+ const freeAllowance =
+ backupAddon?.freeAllowance ?? ADDON_DEFAULTS.backup.freeAllowance;
+ const totalPurchased = backupAddon?.quantity ?? freeAllowance;
+
+ // For MVP: assume 1 backup per allowance
+ // In the future, fetch actual backup count from Hetzner API
+ const estimatedUsed = Math.min(1, freeAllowance);
+ const allowedTotal = totalPurchased;
+ const canCreateMore = estimatedUsed < allowedTotal;
+
+ return Response.json(
+ {
+ allowed: canCreateMore,
+ costPerExtraBackup: ADDON_DEFAULTS.backup.pricePerExtraUnitCents,
+ estimatedUsed,
+ freeAllowance,
+ nextBackupWouldCost: canCreateMore
+ ? 0
+ : ADDON_DEFAULTS.backup.pricePerExtraUnitCents,
+ remainingAllowance: allowedTotal - estimatedUsed,
+ totalAllowed: allowedTotal,
+ },
+ { status: 200 }
+ );
+};
diff --git a/app/api/servers/[id]/backups/route.ts b/app/api/servers/[id]/backups/route.ts
index 0a026b1..3146e6c 100644
--- a/app/api/servers/[id]/backups/route.ts
+++ b/app/api/servers/[id]/backups/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";
+import { checkSubscriptionForServer } from "@/lib/billing/subscription-check";
import { prisma } from "@/lib/db";
import { getProviderForUser } from "@/lib/providers";
import {
@@ -97,6 +98,15 @@ export const POST = async (
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
+ // ⚠️ BILLING: Verify subscription is active before allowing backup creation
+ const subscriptionCheck = await checkSubscriptionForServer(id);
+ if (!subscriptionCheck.isValid) {
+ return NextResponse.json(
+ { error: subscriptionCheck.message },
+ { status: 402 }
+ );
+ }
+
if (!server.providerServerId) {
return NextResponse.json(
{ error: "Server is not provisioned yet" },
diff --git a/app/api/servers/[id]/metrics/live/route.ts b/app/api/servers/[id]/metrics/live/route.ts
new file mode 100644
index 0000000..0c66e89
--- /dev/null
+++ b/app/api/servers/[id]/metrics/live/route.ts
@@ -0,0 +1,76 @@
+import { NextResponse } from "next/server";
+
+import { prisma } from "@/lib/db";
+import { requireUser } from "@/lib/session";
+
+export const runtime = "nodejs";
+
+/**
+ * GET /api/servers/[id]/metrics/live
+ *
+ * Returns current live server metrics (CPU, Memory, Network, etc.)
+ * This endpoint would typically pull from an agent monitoring system
+ * or container monitoring service.
+ *
+ * In a production system, this would:
+ * - Query Prometheus/Grafana
+ * - Call the server agent API
+ * - Poll container stats (docker stats)
+ * - Get game-specific metrics from the server
+ */
+export const GET = async (
+ _request: Request,
+ context: { params: Promise<{ id: string }> }
+) => {
+ const user = await requireUser();
+ const { id } = await context.params;
+
+ const server = await prisma.server.findFirst({
+ select: {
+ id: true,
+ lastHeartbeatAt: true,
+ observedState: true,
+ },
+ where: { deletedAt: null, id, userId: user.id },
+ });
+
+ if (!server) {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+
+ if (server.observedState !== "running") {
+ return NextResponse.json(
+ { error: "Server is not running" },
+ { status: 409 }
+ );
+ }
+
+ // Integrate with monitoring system (Prometheus, agent API, container stats, etc.)
+ // For now, return mock data to demonstrate the API structure
+
+ const uptime = (server.lastHeartbeatAt as Date | null)
+ ? Math.floor(
+ (Date.now() - (server.lastHeartbeatAt as Date).getTime()) / 1000
+ )
+ : 0;
+
+ return NextResponse.json({
+ metrics: {
+ // System metrics (typically from container/host monitoring)
+ // cpu: value from container/host monitoring
+ // memory: value from container/host monitoring
+ // networkIn: bytes per second
+ // networkOut: bytes per second
+ cpu: Math.random() * 50 + 10,
+ memory: Math.random() * 40 + 20,
+ networkIn: Math.random() * 1_000_000,
+ networkOut: Math.random() * 500_000,
+ uptime: Math.max(uptime, 0),
+
+ // Game-specific metrics (if available)
+ // playerCount: 0,
+ // maxPlayers: 32,
+ // tps: 20,
+ },
+ });
+};
diff --git a/app/api/webhooks/stripe/route.ts b/app/api/webhooks/stripe/route.ts
index f74dcac..9ef00a1 100644
--- a/app/api/webhooks/stripe/route.ts
+++ b/app/api/webhooks/stripe/route.ts
@@ -1,7 +1,9 @@
import type { InvoiceStatus, SubscriptionStatus } from "@prisma/client";
+import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import type { Stripe } from "stripe";
+import { start } from "workflow/api";
import { logEvent } from "@/lib/audit";
import { prisma } from "@/lib/db";
@@ -10,9 +12,11 @@ import {
sendInvoicePaidEmail,
sendInvoiceFailedEmail,
sendSuspensionWarningEmail,
+ sendServerCreatedEmail,
} from "@/lib/mail";
-import { SUSPENSION_GRACE_DAYS } from "@/lib/pricing";
+import { ADDON_DEFAULTS, SUSPENSION_GRACE_DAYS } from "@/lib/pricing";
import { stripe } from "@/lib/stripe";
+import { provisionServer } from "@/lib/workflows/provision-server";
/**
* Map a Stripe subscription status to our internal SubscriptionStatus enum.
@@ -361,6 +365,135 @@ const handleInvoicePaymentSucceeded = async (invoice: Stripe.Invoice) => {
}
};
+/** Send the server-created welcome email — errors are silently swallowed */
+const sendCheckoutWelcomeEmail = async (serverId: string) => {
+ const server = await prisma.server.findUnique({
+ select: {
+ game: true,
+ location: true,
+ name: true,
+ user: { select: { email: true, name: true } },
+ },
+ where: { id: serverId },
+ });
+ if (!server?.user) {
+ return;
+ }
+ const appUrl = process.env.BETTER_AUTH_URL ?? "https://panel.nodebyte.host";
+ try {
+ await sendServerCreatedEmail({
+ game: server.game,
+ region: server.location,
+ serverName: server.name,
+ serverUrl: `${appUrl}/dashboard/${serverId}`,
+ toEmail: server.user.email,
+ userName: server.user.name,
+ });
+ } catch {
+ // ignore
+ }
+};
+
+/** Upsert subscription + addons from a completed checkout */
+const upsertCheckoutSubscriptionAndAddons = async (
+ session: Stripe.Checkout.Session,
+ subscriptionId: string,
+ customerId: string
+) => {
+ const serverId = session.metadata?.nodebyteServerId ?? "";
+ const subscription = await stripe.subscriptions.retrieve(subscriptionId);
+ const [firstItem] = subscription.items.data;
+ const pricePerMonthCents = firstItem?.price.unit_amount ?? 0;
+ const stripeProductId =
+ typeof firstItem?.price.product === "string"
+ ? firstItem.price.product
+ : ((firstItem?.price.product as Stripe.Product)?.id ?? "");
+
+ await prisma.subscription.upsert({
+ create: {
+ billingCustomerId: customerId,
+ currency: (subscription.currency ?? "gbp").toUpperCase(),
+ id: subscriptionId,
+ planName: subscription.metadata?.serverType ?? "unknown",
+ pricePerMonthCents,
+ serverId,
+ status: "active",
+ stripePriceId: firstItem?.price.id ?? "",
+ stripeProductId,
+ stripeSubscriptionId: subscriptionId,
+ },
+ update: { status: "active" },
+ where: { stripeSubscriptionId: subscriptionId },
+ });
+
+ await prisma.serverAddon.createMany({
+ data: [
+ {
+ freeAllowance: ADDON_DEFAULTS.backup.freeAllowance,
+ id: `${serverId}-backup`,
+ pricePerUnitCents: ADDON_DEFAULTS.backup.pricePerExtraUnitCents,
+ quantity: ADDON_DEFAULTS.backup.freeAllowance,
+ serverId,
+ subscriptionId,
+ type: "backup",
+ },
+ {
+ freeAllowance: ADDON_DEFAULTS.snapshot.freeAllowance,
+ id: `${serverId}-snapshot`,
+ pricePerUnitCents: ADDON_DEFAULTS.snapshot.pricePerExtraUnitCents,
+ quantity: ADDON_DEFAULTS.snapshot.freeAllowance,
+ serverId,
+ subscriptionId,
+ type: "snapshot",
+ },
+ {
+ freeAllowance: ADDON_DEFAULTS.database.freeAllowance,
+ id: `${serverId}-database`,
+ pricePerUnitCents: ADDON_DEFAULTS.database.pricePerExtraUnitCents,
+ quantity: ADDON_DEFAULTS.database.freeAllowance,
+ serverId,
+ subscriptionId,
+ type: "database",
+ },
+ ],
+ skipDuplicates: true,
+ });
+
+ return serverId;
+};
+
+/** Handle checkout.session.completed — creates subscription/addons and starts provisioning */
+const handleCheckoutSessionCompleted = async (
+ session: Stripe.Checkout.Session
+) => {
+ const serverId = session.metadata?.nodebyteServerId;
+ if (!serverId) {
+ return;
+ }
+
+ const subscriptionId =
+ typeof session.subscription === "string"
+ ? session.subscription
+ : ((session.subscription as Stripe.Subscription | null)?.id ?? null);
+ if (!subscriptionId) {
+ return;
+ }
+
+ const customerId =
+ typeof session.customer === "string"
+ ? session.customer
+ : ((session.customer as Stripe.Customer | null)?.id ?? "");
+
+ await upsertCheckoutSubscriptionAndAddons(
+ session,
+ subscriptionId,
+ customerId
+ );
+ await start(provisionServer, [{ serverId }]);
+ revalidatePath("/dashboard", "layout");
+ await sendCheckoutWelcomeEmail(serverId);
+};
+
/** Handle invoice.payment_failed */
const handleInvoicePaymentFailed = async (invoice: Stripe.Invoice) => {
await upsertInvoice(invoice);
@@ -511,6 +644,12 @@ export const POST = async (req: Request) => {
break;
}
+ case "checkout.session.completed": {
+ const session = event.data.object as Stripe.Checkout.Session;
+ await handleCheckoutSessionCompleted(session);
+ break;
+ }
+
default: {
// Unhandled event — return 200 to prevent Stripe retries
break;
diff --git a/app/dashboard/[id]/actions/rcon.ts b/app/dashboard/[id]/actions/rcon.ts
new file mode 100644
index 0000000..7eee988
--- /dev/null
+++ b/app/dashboard/[id]/actions/rcon.ts
@@ -0,0 +1,70 @@
+"use server";
+
+import { z } from "zod";
+
+import { checkSubscriptionForServer } from "@/lib/billing/subscription-check";
+import { prisma } from "@/lib/db";
+import { requireUser } from "@/lib/session";
+
+const sendRconCommandSchema = z.object({
+ command: z.string().min(1).max(1024),
+ serverId: z.string().min(1),
+});
+
+export type SendRconCommandInput = z.infer;
+
+export type SendRconCommandResult =
+ | { ok: true; commandId: string }
+ | { error: string; ok: false };
+
+/**
+ * Send an RCON command to a running game server.
+ * The command is queued for execution by the server agent.
+ *
+ * @param input - The server ID and command to execute
+ * @returns Success with command ID or error
+ */
+export const sendRconCommand = async (
+ input: SendRconCommandInput
+): Promise => {
+ const user = await requireUser();
+
+ const parsed = sendRconCommandSchema.safeParse(input);
+ if (!parsed.success) {
+ return { error: "Invalid input", ok: false };
+ }
+
+ const server = await prisma.server.findFirst({
+ select: { id: true, observedState: true },
+ where: { deletedAt: null, id: parsed.data.serverId, userId: user.id },
+ });
+
+ if (!server) {
+ return { error: "Server not found", ok: false };
+ }
+
+ if (server.observedState !== "running") {
+ return { error: "Server is not running", ok: false };
+ }
+
+ // ⚠️ BILLING: Verify subscription is active
+ const subscriptionCheck = await checkSubscriptionForServer(
+ parsed.data.serverId
+ );
+ if (!subscriptionCheck.isValid) {
+ return {
+ error:
+ subscriptionCheck.message ??
+ "Subscription is not active for this server",
+ ok: false,
+ };
+ }
+
+ try {
+ // RCON is not yet fully implemented in the protocol
+ // For now, return a not-implemented error
+ return { error: "RCON commands are not yet supported", ok: false };
+ } catch {
+ return { error: "Failed to queue command", ok: false };
+ }
+};
diff --git a/app/dashboard/[id]/components/console-panel.tsx b/app/dashboard/[id]/components/console-panel.tsx
new file mode 100644
index 0000000..7bae5c2
--- /dev/null
+++ b/app/dashboard/[id]/components/console-panel.tsx
@@ -0,0 +1,242 @@
+"use client";
+import { SendIcon } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+import { sendRconCommand } from "../actions/rcon";
+
+interface LogEntry {
+ id: string;
+ seq: number;
+ line: string;
+ stream: "stdout" | "stderr";
+ ts: string;
+}
+
+interface ConsoleLogProps {
+ serverId: string;
+ isServerRunning: boolean;
+}
+
+/**
+ * Real-time console log viewer with RCON command execution
+ *
+ * Features:
+ * - Live log streaming via Server-Sent Events
+ * - Command input with history navigation
+ * - Auto-scroll to latest output
+ * - Color-coded output (stdout vs stderr)
+ * - Terminal-like aesthetics
+ */
+const getLogLineClass = (entry: LogEntry): string => {
+ const baseClass =
+ "font-mono text-sm px-3 py-1 whitespace-pre-wrap break-words";
+ if (entry.stream === "stderr") {
+ return `${baseClass} text-red-400 dark:text-red-500`;
+ }
+ return `${baseClass} text-green-400 dark:text-green-500`;
+};
+
+export const ConsolePanel = ({
+ serverId,
+ isServerRunning,
+}: ConsoleLogProps) => {
+ const [logs, setLogs] = useState([]);
+ const [commandInput, setCommandInput] = useState("");
+ const [commandHistory, setCommandHistory] = useState([]);
+ const [, setHistoryIndex] = useState(-1);
+ const [isSending, setIsSending] = useState(false);
+ const [isConnected, setIsConnected] = useState(false);
+ const logsEndRef = useRef(null);
+ const eventSourceRef = useRef(null);
+
+ // Auto-scroll to bottom
+ const scrollToBottom = useCallback(() => {
+ setTimeout(() => {
+ logsEndRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, 0);
+ }, []);
+
+ // Connect to log stream
+ useEffect(() => {
+ if (!isServerRunning) {
+ setLogs([]);
+ setIsConnected(false);
+ return;
+ }
+
+ const eventSource = new EventSource(
+ `/api/servers/${serverId}/logs/stream?cursor=0`
+ );
+
+ eventSource.addEventListener("log", (event) => {
+ try {
+ const data = JSON.parse(event.data);
+ setLogs((prev) => {
+ // Avoid duplicates by checking seq
+ if (prev.some((log) => log.seq === data.seq)) {
+ return prev;
+ }
+ // Keep last 500 lines
+ return [...prev, data].slice(-500);
+ });
+ scrollToBottom();
+ } catch (error) {
+ console.error("Failed to parse log event:", error);
+ }
+ });
+
+ eventSource.addEventListener("open", () => {
+ setIsConnected(true);
+ });
+
+ eventSource.addEventListener("error", () => {
+ setIsConnected(false);
+ eventSource.close();
+ });
+
+ eventSourceRef.current = eventSource;
+
+ return () => {
+ eventSource.close();
+ eventSourceRef.current = null;
+ };
+ }, [serverId, isServerRunning, scrollToBottom]);
+
+ const handleSendCommand = useCallback(async () => {
+ if (!commandInput.trim() || !isServerRunning) {
+ return;
+ }
+
+ const command = commandInput.trim();
+ setCommandInput("");
+ setHistoryIndex(-1);
+
+ // Add to history
+ setCommandHistory((prev) => [command, ...prev].slice(0, 50));
+
+ setIsSending(true);
+ try {
+ const result = await sendRconCommand({
+ command,
+ serverId,
+ });
+
+ if (result.ok) {
+ toast.success("Command sent");
+ } else {
+ toast.error(result.error);
+ }
+ } catch (error) {
+ toast.error("Failed to send command");
+ console.error(error);
+ } finally {
+ setIsSending(false);
+ }
+ }, [commandInput, serverId, isServerRunning]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleSendCommand();
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setHistoryIndex((prev) => {
+ const nextIndex = prev + 1;
+ if (nextIndex < commandHistory.length) {
+ setCommandInput(commandHistory[nextIndex]);
+ return nextIndex;
+ }
+ return prev;
+ });
+ } else if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setHistoryIndex((prev) => {
+ if (prev > 0) {
+ const nextIndex = prev - 1;
+ setCommandInput(commandHistory[nextIndex]);
+ return nextIndex;
+ } else if (prev === 0) {
+ setCommandInput("");
+ return -1;
+ }
+ return prev;
+ });
+ }
+ },
+ [handleSendCommand, commandHistory]
+ );
+
+ if (!isServerRunning) {
+ return (
+
+
+
+ Console is only available when the server is running.
+
+
+
+ );
+ }
+
+ return (
+
+ {/* Status indicator */}
+
+
+
+ {isConnected ? "Connected" : "Disconnected"}
+
+
+
+ {/* Log display */}
+
+
+ {logs.length === 0 ? (
+
+ Waiting for server output...
+
+ ) : (
+ logs.map((entry) => (
+
+ {entry.line}
+
+ ))
+ )}
+
+
+
+
+ {/* Command input */}
+
+ {
+ setCommandInput(e.target.value);
+ setHistoryIndex(-1);
+ }}
+ />
+
+
+
+
+
+ );
+};
diff --git a/app/dashboard/[id]/components/live-metrics-panel.tsx b/app/dashboard/[id]/components/live-metrics-panel.tsx
new file mode 100644
index 0000000..0f06ce9
--- /dev/null
+++ b/app/dashboard/[id]/components/live-metrics-panel.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import {
+ ActivityIcon,
+ AlertCircleIcon,
+ ArrowDownIcon,
+ ArrowUpIcon,
+ ClockIcon,
+ CpuIcon,
+ MemoryStickIcon,
+ UsersIcon,
+} from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { useLiveMetrics } from "./use-live-metrics";
+
+interface MetricsPanelProps {
+ serverId: string;
+ observedState: string;
+ maxPlayers?: number;
+}
+
+const formatBytes = (bytes: number): string => {
+ if (bytes >= 1e6) {
+ return `${(bytes / 1e6).toFixed(1)} MB/s`;
+ }
+ if (bytes >= 1e3) {
+ return `${(bytes / 1e3).toFixed(1)} KB/s`;
+ }
+ return `${Math.round(bytes)} B/s`;
+};
+
+const formatUptime = (seconds: number): string => {
+ const days = Math.floor(seconds / 86_400);
+ const hours = Math.floor((seconds % 86_400) / 3600);
+ const mins = Math.floor((seconds % 3600) / 60);
+ if (days > 0) {
+ return `${days}d ${hours}h`;
+ }
+ if (hours > 0) {
+ return `${hours}h ${mins}m`;
+ }
+ return `${mins}m`;
+};
+
+const progressColor = (pct: number): string => {
+ if (pct < 60) {
+ return "bg-emerald-500";
+ }
+ if (pct < 85) {
+ return "bg-amber-500";
+ }
+ return "bg-red-500";
+};
+
+const MetricItem = ({
+ icon,
+ label,
+ value,
+ pct,
+ mono,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ value: string;
+ pct?: number;
+ mono?: boolean;
+}) => (
+
+
+ {icon}
+ {label}
+
+
+ {value}
+
+ {pct !== undefined && (
+
+ )}
+
+);
+
+export const LiveMetricsPanel = ({
+ serverId,
+ observedState,
+ maxPlayers,
+}: MetricsPanelProps) => {
+ const { metrics, loading, error } = useLiveMetrics(serverId, observedState);
+
+ if (observedState !== "running") {
+ return null;
+ }
+
+ if (error) {
+ return (
+
+
+
Unable to load metrics
+
+ );
+ }
+
+ if (loading || !metrics) {
+ return (
+
+ );
+ }
+
+ return (
+
+ }
+ label="CPU"
+ pct={metrics.cpu}
+ value={`${metrics.cpu.toFixed(1)}%`}
+ />
+ }
+ label="Memory"
+ pct={metrics.memory}
+ value={`${metrics.memory.toFixed(1)}%`}
+ />
+ }
+ label="In"
+ mono
+ value={formatBytes(metrics.networkIn)}
+ />
+ }
+ label="Out"
+ mono
+ value={formatBytes(metrics.networkOut)}
+ />
+ {metrics.playerCount !== undefined && (
+ }
+ label="Players"
+ value={
+ maxPlayers
+ ? `${metrics.playerCount}/${maxPlayers}`
+ : String(metrics.playerCount)
+ }
+ />
+ )}
+ {metrics.tps !== undefined && (
+ }
+ label="TPS"
+ value={metrics.tps.toFixed(1)}
+ />
+ )}
+ }
+ label="Uptime"
+ value={formatUptime(metrics.uptime)}
+ />
+
+ );
+};
diff --git a/app/dashboard/[id]/components/shell.tsx b/app/dashboard/[id]/components/shell.tsx
index 80b76e6..8674fc5 100644
--- a/app/dashboard/[id]/components/shell.tsx
+++ b/app/dashboard/[id]/components/shell.tsx
@@ -30,9 +30,9 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { games } from "@/games";
import type { CatalogServerType } from "@/lib/providers/types";
@@ -57,8 +57,22 @@ const PROVISIONING_PHASES = new Set([
"errored",
]);
+const STATE_BADGE: Record = {
+ deleting:
+ "border-red-500/40 bg-red-500/10 text-red-600 dark:bg-red-500/15 dark:text-red-400",
+ failed:
+ "border-red-500/40 bg-red-500/10 text-red-600 dark:bg-red-500/15 dark:text-red-400",
+ lost: "border-red-500/40 bg-red-500/10 text-red-600 dark:bg-red-500/15 dark:text-red-400",
+ running:
+ "border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-400",
+ stopped:
+ "border-zinc-500/40 bg-zinc-500/10 text-zinc-500 dark:bg-zinc-500/15 dark:text-zinc-400",
+ unhealthy:
+ "border-amber-500/40 bg-amber-500/10 text-amber-600 dark:bg-amber-500/15 dark:text-amber-400",
+};
+
const ALL_TABS = [
- { label: "Connect", minRole: "viewer" as ServerRole, value: "connect" },
+ { label: "Overview", minRole: "viewer" as ServerRole, value: "connect" },
{ label: "Activity", minRole: "viewer" as ServerRole, value: "activity" },
{ label: "Console", minRole: "viewer" as ServerRole, value: "console" },
{ label: "Graphs", minRole: "viewer" as ServerRole, value: "graphs" },
@@ -87,27 +101,17 @@ interface Props {
children: ReactNode;
}
-const stateBadgeClass = (state: string, deleting: boolean): string => {
- if (deleting || state === "failed" || state === "lost") {
- return "";
- }
- if (state === "running") {
- return "border-emerald-600 bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400";
+const getStatusDotColor = (key: string) => {
+ if (key === "running") {
+ return "bg-emerald-500";
}
- return "";
-};
-
-const stateBadgeVariant = (
- state: string,
- deleting: boolean
-): "default" | "secondary" | "destructive" | "outline" => {
- if (deleting || state === "failed" || state === "lost") {
- return "destructive";
+ if (key === "unhealthy") {
+ return "bg-amber-500";
}
- if (state === "unhealthy") {
- return "secondary";
+ if (["failed", "lost", "deleting"].includes(key)) {
+ return "bg-red-500";
}
- return "outline";
+ return "bg-zinc-400";
};
export const ServerShell = ({
@@ -129,6 +133,7 @@ export const ServerShell = ({
const [server, setServer] = useState(initial);
const [pending, setPending] = useState(null);
const [deleteOpen, setDeleteOpen] = useState(false);
+ const [deleteConfirmName, setDeleteConfirmName] = useState("");
useEffect(() => {
const t = setInterval(async () => {
@@ -182,6 +187,13 @@ export const ServerShell = ({
const updateServer = (patch: Partial) =>
setServer((prev) => ({ ...prev, ...patch }));
+ const handleDeleteOpenChange = (open: boolean) => {
+ setDeleteOpen(open);
+ if (!open) {
+ setDeleteConfirmName("");
+ }
+ };
+
const isProvisioning = PROVISIONING_PHASES.has(server.phase);
const game = games.find((g) => g.id === server.game);
@@ -190,80 +202,99 @@ export const ServerShell = ({
}
const deleting = server.desiredState === "deleted";
- const statusLabel = deleting ? "deleting" : server.observedState;
+ const statusKey = deleting ? "deleting" : server.observedState;
+ const statusLabel = statusKey.charAt(0).toUpperCase() + statusKey.slice(1);
const meta = (
+
{statusLabel}
);
const actions = (
-
-
-
-
-
-
-
- sendCommand("START")}
- >
-
- Start
-
- sendCommand("STOP")}
+
+ {canControl && server.observedState === "stopped" && (
+
sendCommand("START")}
>
-
- Stop
-
- sendCommand("RESTART")}
- >
-
- Restart
-
- {canDelete && (
- <>
-
+
+ Start
+
+ )}
+ {canControl && server.observedState === "running" && (
+ <>
+
sendCommand("RESTART")}
+ >
+
+ Restart
+
+
sendCommand("STOP")}
+ >
+
+ Stop
+
+ >
+ )}
+ {pending && (
+
+ {pending.toLowerCase()}…
+
+ )}
+ {canDelete && (
+
+
+
+
+
+
+
setDeleteOpen(true)}
variant="destructive"
>
- Delete
+ Delete server
- >
- )}
-
-
+
+
+ )}
+
);
const deleteDialog = (
-
+
Delete this server?
@@ -272,9 +303,30 @@ export const ServerShell = ({
permanently deleted.
+
+
+ Type{" "}
+ {server.name}{" "}
+ to confirm.
+
+
setDeleteConfirmName(event.target.value)}
+ />
+
Cancel
- Delete
+
+ {pending === "DELETE" ? "Deleting..." : "Delete"}
+
@@ -323,31 +375,33 @@ export const ServerShell = ({
title={server.name}
>
-
- {visibleTabs.map((tab) => (
-
-
- {tab.value === "team" ? (
-
-
- Team
-
- ) : (
- tab.label
- )}
-
-
- ))}
-
+
+
+ {visibleTabs.map((tab) => (
+
+
+ {tab.value === "team" ? (
+
+
+ Team
+
+ ) : (
+ tab.label
+ )}
+
+
+ ))}
+
+
diff --git a/app/dashboard/[id]/components/team-panel.tsx b/app/dashboard/[id]/components/team-panel.tsx
index d878e49..f65e8b3 100644
--- a/app/dashboard/[id]/components/team-panel.tsx
+++ b/app/dashboard/[id]/components/team-panel.tsx
@@ -7,13 +7,6 @@ import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
import {
Dialog,
DialogContent,
@@ -190,13 +183,14 @@ export const TeamPanel = ({
return (
-
-
+ {/* Team members */}
+
+
-
Team members
-
+ Team members
+
Manage who has access to this server.
-
+
-
-
+
+
+
{/* Owner row */}
-
+
@@ -273,7 +268,7 @@ export const TeamPanel = ({
{owner.name ?? owner.email}
{owner.name && (
-
+
{owner.email}
)}
@@ -291,7 +286,7 @@ export const TeamPanel = ({
{members.map((member) => (
@@ -300,7 +295,7 @@ export const TeamPanel = ({
{member.user.name ?? member.user.email}
{member.user.name && (
-
+
{member.user.email}
)}
@@ -350,31 +345,31 @@ export const TeamPanel = ({
))}
{members.length === 0 && (
-
+
No members yet. Invite someone to get started.
)}
-
-
+
+
{/* Pending invites */}
{invites.length > 0 && (
-
-
- Pending invites
-
+
+
+
Pending invites
+
These invites have not been accepted yet.
-
-
-
+
+
+
{invites.map((invite) => (
{invite.email}
-
+
Expires {new Date(invite.expiresAt).toLocaleDateString()}
@@ -391,8 +386,8 @@ export const TeamPanel = ({
))}
-
-
+
+
)}
);
diff --git a/app/dashboard/[id]/components/use-live-metrics.ts b/app/dashboard/[id]/components/use-live-metrics.ts
new file mode 100644
index 0000000..33f72b8
--- /dev/null
+++ b/app/dashboard/[id]/components/use-live-metrics.ts
@@ -0,0 +1,97 @@
+"use client";
+import { useCallback, useEffect, useState } from "react";
+
+/**
+ * Live metrics snapshot - shows current system state
+ * Polled at regular intervals when server is running
+ */
+export interface LiveMetrics {
+ // Percentage 0-100
+ cpu: number;
+ // Percentage 0-100
+ memory: number;
+ // Bytes per second
+ networkIn: number;
+ // Bytes per second
+ networkOut: number;
+ // Seconds
+ uptime: number;
+ // Current players
+ playerCount?: number;
+ // Max players
+ maxPlayers?: number;
+ // Ticks per second (if available)
+ tps?: number;
+}
+
+export interface UseLiveMetricsReturn {
+ metrics: LiveMetrics | null;
+ loading: boolean;
+ error: string | null;
+ refresh: () => Promise
;
+}
+
+/**
+ * Hook for fetching and polling live server metrics
+ * Automatically refreshes every pollInterval ms when server is running
+ */
+export const useLiveMetrics = (
+ serverId: string,
+ observedState: string,
+ pollInterval = 5000
+): UseLiveMetricsReturn => {
+ const [metrics, setMetrics] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [errorMessage, setErrorMessage] = useState(null);
+
+ const fetchMetrics = useCallback(async () => {
+ if (observedState !== "running") {
+ setMetrics(null);
+ setLoading(false);
+ return;
+ }
+
+ try {
+ setErrorMessage(null);
+ const response = await fetch(`/api/servers/${serverId}/metrics/live`, {
+ cache: "no-store",
+ });
+
+ if (!response.ok) {
+ if (response.status === 404) {
+ // Endpoint doesn't exist yet or server has no metrics
+ setMetrics(null);
+ } else {
+ throw new Error("Failed to fetch metrics");
+ }
+ return;
+ }
+
+ const data = await response.json();
+ setMetrics(data.metrics || null);
+ } catch (error) {
+ setErrorMessage(error instanceof Error ? error.message : "Unknown error");
+ setMetrics(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [serverId, observedState]);
+
+ useEffect(() => {
+ if (observedState !== "running") {
+ setMetrics(null);
+ setLoading(false);
+ return;
+ }
+
+ // Initial fetch
+ fetchMetrics();
+
+ // Set up polling
+ const interval = setInterval(fetchMetrics, pollInterval);
+
+ return () => clearInterval(interval);
+ }, [serverId, observedState, pollInterval, fetchMetrics]);
+
+ return { error: errorMessage, loading, metrics, refresh: fetchMetrics };
+};
diff --git a/app/dashboard/[id]/console/page.tsx b/app/dashboard/[id]/console/page.tsx
index 9ce77c9..bc31426 100644
--- a/app/dashboard/[id]/console/page.tsx
+++ b/app/dashboard/[id]/console/page.tsx
@@ -1,10 +1,164 @@
"use client";
+import { HistoryIcon, SendIcon, TerminalIcon } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+
+import { sendRconCommand } from "../actions/rcon";
+import { LiveMetricsPanel } from "../components/live-metrics-panel";
import { LogsStream } from "../components/logs-stream";
import { useServer } from "../components/server-context";
const ConsoleTab = () => {
const { server } = useServer();
- return ;
+ const [commandInput, setCommandInput] = useState("");
+ const [commandHistory, setCommandHistory] = useState([]);
+ const [, setHistoryIndex] = useState(-1);
+ const [isSending, setIsSending] = useState(false);
+
+ const handleSendCommand = async () => {
+ if (!commandInput.trim() || server.observedState !== "running") {
+ return;
+ }
+
+ const command = commandInput.trim();
+ setCommandInput("");
+ setHistoryIndex(-1);
+
+ setCommandHistory((prev) => [command, ...prev].slice(0, 50));
+
+ setIsSending(true);
+ try {
+ const result = await sendRconCommand({ command, serverId: server.id });
+ if (result.ok) {
+ toast.success("Command sent");
+ } else {
+ toast.error(result.error);
+ }
+ } catch (error) {
+ toast.error("Failed to send command");
+ console.error(error);
+ } finally {
+ setIsSending(false);
+ }
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void handleSendCommand();
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setHistoryIndex((prev) => {
+ const next = prev + 1;
+ if (next < commandHistory.length) {
+ setCommandInput(commandHistory[next]);
+ return next;
+ }
+ return prev;
+ });
+ } else if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setHistoryIndex((prev) => {
+ if (prev > 0) {
+ const next = prev - 1;
+ setCommandInput(commandHistory[next]);
+ return next;
+ } else if (prev === 0) {
+ setCommandInput("");
+ return -1;
+ }
+ return prev;
+ });
+ }
+ };
+
+ const isRunning = server.observedState === "running";
+
+ return (
+
+ {/* Live metrics — compact bar when running */}
+ {isRunning && (
+
+
+
+ )}
+
+ {/* Terminal window */}
+
+ {/* Terminal title bar */}
+
+
+
{server.name}
+
+
+
+ {isRunning ? "live" : server.observedState}
+
+ {commandHistory.length > 0 && (
+
+
+ {commandHistory.length}
+
+ )}
+
+
+
+ {/* Log output — fills remaining space */}
+
+
+
+
+ {/* Command input */}
+ {isRunning ? (
+
+
+ $
+
+ {
+ setCommandInput(e.target.value);
+ setHistoryIndex(-1);
+ }}
+ onKeyDown={handleKeyDown}
+ />
+ void handleSendCommand()}
+ >
+
+
+
+ ) : (
+
+
+ Server is {server.observedState}. Start the server to send
+ commands.
+
+
+ )}
+
+
+ );
};
export default ConsoleTab;
diff --git a/app/dashboard/account/billing/page.tsx b/app/dashboard/account/billing/page.tsx
index 4a45ad5..5277f01 100644
--- a/app/dashboard/account/billing/page.tsx
+++ b/app/dashboard/account/billing/page.tsx
@@ -1,47 +1,80 @@
-import { AlertCircle, CheckCircle2, CreditCard, XCircle } from "lucide-react";
+import {
+ AlertCircle,
+ CheckCircle2,
+ CreditCard,
+ XCircle,
+ TrendingUp,
+ ArrowRight,
+} from "lucide-react";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
import { prisma } from "@/lib/db";
import { formatNodeBytePrice } from "@/lib/pricing";
import { requireUser } from "@/lib/session";
+import { cn } from "@/lib/utils";
-import { PageBody, PageHeader } from "../../components/page-header";
+import { PageBody } from "../../components/page-header";
import { CustomerPortalButton } from "../components/customer-portal-button";
const statusConfig = {
- active: { color: "text-green-500", icon: CheckCircle2, label: "Active" },
+ active: {
+ bg: "bg-emerald-500/10 border-emerald-500/30",
+ color: "text-emerald-600 dark:text-emerald-400",
+ dot: "bg-emerald-500",
+ icon: CheckCircle2,
+ label: "Active",
+ },
canceled: {
- color: "text-muted-foreground",
+ bg: "bg-zinc-500/10 border-zinc-500/30",
+ color: "text-zinc-500 dark:text-zinc-400",
+ dot: "bg-zinc-400",
icon: XCircle,
label: "Canceled",
},
incomplete: {
- color: "text-amber-500",
+ bg: "bg-amber-500/10 border-amber-500/30",
+ color: "text-amber-600 dark:text-amber-400",
+ dot: "bg-amber-500",
icon: AlertCircle,
label: "Incomplete",
},
incomplete_expired: {
- color: "text-destructive",
+ bg: "bg-red-500/10 border-red-500/30",
+ color: "text-red-600 dark:text-red-400",
+ dot: "bg-red-500",
icon: XCircle,
label: "Expired",
},
- past_due: { color: "text-destructive", icon: AlertCircle, label: "Past due" },
+ past_due: {
+ bg: "bg-red-500/10 border-red-500/30",
+ color: "text-red-600 dark:text-red-400",
+ dot: "bg-red-500",
+ icon: AlertCircle,
+ label: "Past due",
+ },
paused: {
- color: "text-muted-foreground",
+ bg: "bg-zinc-500/10 border-zinc-500/30",
+ color: "text-zinc-500 dark:text-zinc-400",
+ dot: "bg-zinc-400",
icon: AlertCircle,
label: "Paused",
},
- trialing: { color: "text-blue-500", icon: CheckCircle2, label: "Trial" },
- unpaid: { color: "text-destructive", icon: AlertCircle, label: "Unpaid" },
+ trialing: {
+ bg: "bg-blue-500/10 border-blue-500/30",
+ color: "text-blue-600 dark:text-blue-400",
+ dot: "bg-blue-500",
+ icon: CheckCircle2,
+ label: "Trial",
+ },
+ unpaid: {
+ bg: "bg-red-500/10 border-red-500/30",
+ color: "text-red-600 dark:text-red-400",
+ dot: "bg-red-500",
+ icon: AlertCircle,
+ label: "Unpaid",
+ },
} as const;
const BillingPage = async () => {
@@ -66,153 +99,178 @@ const BillingPage = async () => {
(s) => s.status !== "active" && s.status !== "trialing"
) ?? [];
+ const totalMonthlyCents = activeSubscriptions.reduce(
+ (sum, s) => sum + s.pricePerMonthCents,
+ 0
+ );
+
return (
- <>
-
-
- Manage your NodeByte subscriptions and payment details.
-
-
-
-
- {/* Summary banner */}
-
-
-
+
+
+ {/* Summary card */}
+
+
+
+
+
+
-
- Payment & subscriptions
-
-
+
{activeSubscriptions.length > 0
? `${activeSubscriptions.length} active plan${activeSubscriptions.length > 1 ? "s" : ""}`
: "No active subscriptions"}
-
-
- {billingCustomer && (
-
-
-
- )}
-
-
-
- {/* Active subscriptions */}
- {activeSubscriptions.length > 0 && (
-
-
Active plans
-
- {activeSubscriptions.map((sub) => {
- const cfg =
- statusConfig[sub.status as keyof typeof statusConfig] ??
- statusConfig.incomplete;
- const StatusIcon = cfg.icon;
- return (
-
-
-
-
-
-
- {sub.server?.name ?? "Unknown server"}
-
-
- {sub.planName} · {sub.server?.game ?? ""}
-
-
-
-
- {sub.currentPeriodEnd && (
-
- Renews{" "}
- {sub.currentPeriodEnd.toLocaleDateString(
- "en-US",
- {
- day: "numeric",
- month: "short",
- year: "numeric",
- }
- )}
-
- )}
-
- {formatNodeBytePrice(sub.pricePerMonthCents)}/mo
-
- {sub.server && (
-
-
- Manage
-
-
- )}
-
-
-
- );
- })}
+
+ {activeSubscriptions.length > 0 && (
+
+
+ {formatNodeBytePrice(totalMonthlyCents)}
+ {" "}
+ / month total
+
+ )}
- )}
+ {billingCustomer && (
+
+ )}
+
+
- {/* Past subscriptions */}
- {inactiveSubscriptions.length > 0 && (
-
-
- Past subscriptions
-
-
- {inactiveSubscriptions.map((sub) => {
- const cfg =
- statusConfig[sub.status as keyof typeof statusConfig] ??
- statusConfig.canceled;
- const StatusIcon = cfg.icon;
- return (
-
-
-
-
-
- {sub.server?.name ?? "Unknown server"}
-
-
- {sub.planName} · {cfg.label}
+ {/* Active subscriptions */}
+ {activeSubscriptions.length > 0 && (
+
+
+ Active plans
+
+
+ {activeSubscriptions.map((sub) => {
+ const cfg =
+ statusConfig[sub.status as keyof typeof statusConfig] ??
+ statusConfig.incomplete;
+ return (
+
+
+
+
+
+
+
+ {sub.server?.name ?? "Unknown server"}
+
+
+ {sub.planName}
+ {sub.server?.game && ` · ${sub.server.game}`}
+
+
+
+
+
+
+ {formatNodeBytePrice(sub.pricePerMonthCents)}/mo
+
+ {sub.currentPeriodEnd && (
+
+ Renews{" "}
+ {sub.currentPeriodEnd.toLocaleDateString("en-US", {
+ day: "numeric",
+ month: "short",
+ })}
-
+ )}
- {formatNodeBytePrice(sub.pricePerMonthCents)}/mo
+
+ {cfg.label}
+ {sub.server && (
+
+
+
+
+
+ )}
- );
- })}
-
+
+ );
+ })}
+
+
+ )}
+
+ {/* Past subscriptions */}
+ {inactiveSubscriptions.length > 0 && (
+
+
+ Past plans
+
+
+ {inactiveSubscriptions.map((sub) => {
+ const cfg =
+ statusConfig[sub.status as keyof typeof statusConfig] ??
+ statusConfig.canceled;
+ return (
+
+
+
+ {sub.server?.name ?? "Unknown server"}
+
+
+ {sub.planName} · {cfg.label}
+
+
+
+ {formatNodeBytePrice(sub.pricePerMonthCents)}/mo
+
+
+ );
+ })}
- )}
+
+ )}
- {/* Empty state */}
- {!billingCustomer || billingCustomer.subscriptions.length === 0 ? (
-
-
-
No subscriptions yet
-
+ {/* Empty state */}
+ {!billingCustomer || billingCustomer.subscriptions.length === 0 ? (
+
+
+
+
+
+
No subscriptions yet
+
Create your first game server to get started.
-
- Deploy a server
-
- ) : null}
-
-
- >
+
+ Deploy a server
+
+
+ ) : null}
+
+
);
};
diff --git a/app/dashboard/account/components/passkeys-panel.tsx b/app/dashboard/account/components/passkeys-panel.tsx
index dce6265..f87247b 100644
--- a/app/dashboard/account/components/passkeys-panel.tsx
+++ b/app/dashboard/account/components/passkeys-panel.tsx
@@ -116,10 +116,10 @@ export const PasskeysPanel = () => {
);
}
return (
-
+
{passkeys.map((passkey) => (
@@ -149,7 +149,8 @@ export const PasskeysPanel = () => {
return (
<>
-
+
+
Passkeys
{renderList()}
setAddOpen(true)}
diff --git a/app/dashboard/account/components/password-panel.tsx b/app/dashboard/account/components/password-panel.tsx
index 046a82e..77cbf22 100644
--- a/app/dashboard/account/components/password-panel.tsx
+++ b/app/dashboard/account/components/password-panel.tsx
@@ -35,44 +35,47 @@ export const PasswordPanel = () => {
};
return (
-
+
);
};
diff --git a/app/dashboard/account/components/profile-panel.tsx b/app/dashboard/account/components/profile-panel.tsx
index cf95068..563ff20 100644
--- a/app/dashboard/account/components/profile-panel.tsx
+++ b/app/dashboard/account/components/profile-panel.tsx
@@ -116,19 +116,23 @@ export const ProfilePanel = ({ user }: Props) => {
};
return (
-