import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { mcProcessManager } from "@/lib/minecraft/process"; import { checkRateLimit, getClientIp } from "@/lib/security/rateLimit"; import * as os from "node:os"; export async function GET(req: NextRequest) { const session = await auth.api.getSession({ headers: req.headers }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); const ip = getClientIp(req); const { allowed } = checkRateLimit(ip); if (!allowed) return NextResponse.json({ error: "Too many requests" }, { status: 429 }); const totalMemMb = Math.round(os.totalmem() / 1024 / 1024); const freeMemMb = Math.round(os.freemem() / 1024 / 1024); const usedMemMb = totalMemMb - freeMemMb; // CPU usage (average across all cores, sampled over 100ms) const cpuPercent = await getCpuPercent(); const serverStatus = mcProcessManager.getStatus(); return NextResponse.json({ system: { cpuPercent, totalMemMb, usedMemMb, freeMemMb, loadAvg: os.loadavg(), uptime: os.uptime(), platform: os.platform(), arch: os.arch(), }, server: serverStatus, timestamp: Date.now(), }); } function getCpuPercent(): Promise { return new Promise((resolve) => { const cpus1 = os.cpus(); setTimeout(() => { const cpus2 = os.cpus(); let totalIdle = 0; let totalTick = 0; for (let i = 0; i < cpus1.length; i++) { const cpu1 = cpus1[i].times; const cpu2 = cpus2[i].times; const idle = cpu2.idle - cpu1.idle; const total = (cpu2.user - cpu1.user) + (cpu2.nice - cpu1.nice) + (cpu2.sys - cpu1.sys) + (cpu2.idle - cpu1.idle) + ((cpu2.irq ?? 0) - (cpu1.irq ?? 0)); totalIdle += idle; totalTick += total; } const percent = totalTick === 0 ? 0 : Math.round(((totalTick - totalIdle) / totalTick) * 100); resolve(percent); }, 100); }); }